Phani
Phani

Reputation: 3315

How to make a set of lists

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?

Upvotes: 74

Views: 144476

Answers (4)

sohrab haghayegh
sohrab haghayegh

Reputation: 31

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)

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

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

Upvotes: 7

Alberto Coletta
Alberto Coletta

Reputation: 1593

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)}

Upvotes: 6

Anshul Goyal
Anshul Goyal

Reputation: 76857

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)}

Upvotes: 115

Related Questions