Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a set of lists

Tags:

python

list

set

I have a list of lists like this:

i = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]

I would like to get a list containing "unique" lists (based on their elements) like:

o = [[1, 2, 3], [2, 4, 5]]

I cannot use set() as there are non-hashable elements in the list. Instead, I am doing this:

o = []
for e in i:
  if e not in o:
    o.append(e)

Is there an easier way to do this?

like image 791
Phani Avatar asked Nov 06 '14 15:11

Phani


People also ask

How do I create a list set?

Using set() Function This approach is one of the simplest methods of converting a list into a set. All you need is to use the set() constructor and pass the list as an argument. Syntax: set(list). Created a list having few elements.

Can we make set of lists?

You can create a set of tuples, a set of lists will not be possible because of non hashable elements as you mentioned.

How do you make a list of lists in Python?

In Python, we can create a list by surrounding all the elements with square brackets [] and each element separated by commas. It can be used to store integer, float, string and more.

Can I have a set of lists Python?

Therefore, Python does not allow a set to store a list. You cannot add a list to a set. A set is an unordered collection of distinct hashable objects.


4 Answers

You can create a set of tuples, a set of lists will not be possible because of non hashable elements as you mentioned.

>>> l = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]
>>> set(tuple(i) for i in l)
{(1, 2, 3), (2, 4, 5)}
like image 67
Anshul Goyal Avatar answered Oct 08 '22 10:10

Anshul Goyal


i = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]

print([ele for ind, ele in enumerate(i) if ele not in i[:ind]])
[[1, 2, 3], [2, 4, 5]]

If you consider [2, 4, 5] to be equal to [2, 5, 4] then you will need to do further checks

like image 39
Padraic Cunningham Avatar answered Oct 08 '22 12:10

Padraic Cunningham


You can convert each element to a tuple and then insert it in a set.

Here's some code with your example:

tmp = set()
a = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]
for i in a:
    tmp.add(tuple(i))

tmp will be like this:

{(1, 2, 3), (2, 4, 5)}
like image 5
boh717 Avatar answered Oct 08 '22 12:10

boh717


Here's another way to do it:

I = [[1, 2, 3], [2, 4, 5], [1, 2, 3], [2, 4, 5]]
mySet = set()

for j in range(len(I)):
  mySet = mySet | set([tuple(I[j])])

print(mySet)
like image 1
sohrab haghayegh Avatar answered Oct 08 '22 11:10

sohrab haghayegh