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!
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.
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.
📢 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.
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] .
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 set
s 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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With