Tested on Python 2.6 interpreter:
>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> a.add(l)
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
a.add(l)
TypeError: list objects are unhashable
I think that I can't add the list to the set because there's no way Python can tell If I have added the same list twice. Is there a workaround?
EDIT: I want to add the list itself, not its elements.
Here is how I usually do it:
To add the elements of a list to a set, use
update
From https://docs.python.org/2/library/sets.html
E.g.
If you instead want to add the entire list as a single element to the set, you can't because lists aren't hashable. You could instead add a tuple, e.g.
s.add(tuple(l))
. See also TypeError: unhashable type: 'list' when using built-in set function for more information on that.Hopefully this helps:
This should do:
You can't add a list to a set because lists are mutable, meaning that you can change the contents of the list after adding it to the set.
You can however add tuples to the set, because you cannot change the contents of a tuple:
Edit: some explanation: The documentation defines a
set
as an unordered collection of distinct hashable objects. The objects have to be hashable so that finding, adding and removing elements can be done faster than looking at each individual element every time you perform these operations. The specific algorithms used are explained in the Wikipedia article. Pythons hashing algorithms are explained on effbot.org and pythons__hash__
function in the python reference.Some facts:
list
: usetuple
insteadset
: usefrozenset
insteaddict
: has no official counterpart, but there are some recipesI found I needed to do something similar today. The algorithm knew when it was creating a new list that needed to added to the set, but not when it would have finished operating on the list.
Anyway, the behaviour I wanted was for set to use
id
rather thanhash
. As such I foundmydict[id(mylist)] = mylist
instead ofmyset.add(mylist)
to offer the behaviour I wanted.