Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set of list of lists in python

Tags:

python

list

set

I am having a list of lists :

mat = [[1,2,3],[4,5,6],[1,2,3],[7,8,9],[4,5,6]] 

and I want to convert into a set i.e. remove the repeating lists and creating a new list out of it which will only contain the unique lists.

In above case the required answer will be

[[1,2,3],[4,5,6],[7,8,9]] 

But when I do set(mat), it gives me error

TypeError: unhashable type: 'list'

Can you please solve my problem. Thanks in advance!

like image 416
Mayank Jain Avatar asked Oct 22 '14 18:10

Mayank Jain


People also ask

Can you have a list of list of lists in Python?

Python provides an option of creating a list within a list. If put simply, it is a nested list but with one or more lists inside as an element.

Can you have a set of lists in 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.

How do you combine lists within a list Python?

📢 TLDR: Use + In almost all simple situations, using list1 + list2 is the way you want to concatenate lists. The edge cases below are better in some situations, but + is generally the best choice. All options covered work in Python 2.3, Python 2.7, and all versions of Python 31.

How do you create a set from two lists in Python?

To perform the union of two lists in python, we just have to create an output list that should contain elements from both the input lists. For instance, if we have list1=[1,2,3,4,5,6] and list2=[2,4,6,8,10,12] , the union of list1 and list2 will be [1,2,3,4,5,6,8,10,12] .


1 Answers

Since the lists are mutable, they cannot be hashed. The best bet is to convert them to a tuple and form a set, like this

>>> mat = [[1,2,3],[4,5,6],[1,2,3],[7,8,9],[4,5,6]] >>> set(tuple(row) for row in mat) set([(4, 5, 6), (7, 8, 9), (1, 2, 3)]) 

We iterate through the mat, one list at a time, convert that to a tuple (which is immutable, so sets are cool with them) and the generator is sent to the set function.

If you want the result as list of lists, you can extend the same, by converting the result of set function call, to lists, like this

>>> [list(item) for item in set(tuple(row) for row in mat)] [[4, 5, 6], [7, 8, 9], [1, 2, 3]] 
like image 102
thefourtheye Avatar answered Sep 23 '22 17:09

thefourtheye