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.
You cannot add a list to a set. A set is an unordered collection of distinct hashable objects.
To add a list to set in Python, use the set. update() function. The set. update() is a built-in Python function that accepts a single element or multiple iterable sequences as arguments and adds that to the set.
Add all items in list to set using add() & for loop. Iterate over all the items in the list using a for loop and pass each item as an argument to the add() function. If that item is not already present in the set, then it will be added to the set i.e.
Use set.update()
or |=
>>> a = set('abc') >>> l = ['d', 'e'] >>> a.update(l) >>> a {'e', 'b', 'c', 'd', 'a'} >>> l = ['f', 'g'] >>> a |= set(l) >>> a {'e', 'b', 'f', 'c', 'd', 'g', 'a'}
edit: If you want to add the list itself and not its members, then you must use a tuple, unfortunately. Set members must be hashable.
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