Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a set of 2d list in python

I have a list like follows:

t=[[1, 7], [3, 7], [1, 7], [5, 8], [3, 7]]

I need to get a set out of this so the output would be like:

t=[[1, 7], [3, 7], [5, 8]]

I tried to use t = set(t) but it didn't work.

like image 456
Asce4s Avatar asked Oct 17 '25 18:10

Asce4s


2 Answers

If you do not care about the order, you can first convert the inner lists to tuples using map() function, and then convert them to set and then back to list .

Example -

>>> t=[[1, 7], [3, 7], [1, 7], [5, 8], [3, 7]]
>>> t = list(set(map(tuple,t)))
>>> t
[(3, 7), (5, 8), (1, 7)]
like image 105
Anand S Kumar Avatar answered Oct 20 '25 07:10

Anand S Kumar


The problem is that, lists are mutable and thus one cannot make a set out of them as they might change. Thus you want to use tuples which are immutable. Thus you can use:

list(set([tuple(ti) for ti in t]))
like image 35
cr1msonB1ade Avatar answered Oct 20 '25 06:10

cr1msonB1ade