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.
The union operator is much faster than add anyway.
edit: If you want the list itself and not its members, then you must use a tuple, unfortunately. Set members must be hashable.
Sets can't have mutable (changeable) elements/members. A list, being mutable, cannot be a member of a set.
As sets are mutable, you cannot have a set of sets! You can have a set of frozensets though.
(The same kind of "mutability requirement" applies to the keys of a dict.)
Other answers have already given you code, I hope this gives a bit of insight. I'm hoping Alex Martelli will answer with even more details.
list objects are unhashable. you might want to turn them in to tuples though.
You want to add a tuple, not a list:
If you have a list, you can convert to the tuple, as shown above. A tuple is immutable, so it can be added to the set.
Please notice the function
set.update()
. The documentation says:You'll want to use tuples, which are hashable (you can't hash a mutable object like a list).