Add list to set?
Solution 1:
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.
Solution 2:
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:
>>> a.add(('f', 'g'))
>>> print a
set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])
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:
- Set elements as well as dictionary keys have to be hashable
- Some unhashable datatypes:
-
list
: usetuple
instead -
set
: usefrozenset
instead -
dict
: has no official counterpart, but there are some recipes
-
- Object instances are hashable by default with each instance having a unique hash. You can override this behavior as explained in the python reference.
Solution 3:
To add the elements of a list to a set, use update
From https://docs.python.org/2/library/sets.html
s.update(t): return set s with elements added from t
E.g.
>>> s = set([1, 2])
>>> l = [3, 4]
>>> s.update(l)
>>> s
{1, 2, 3, 4}
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.
Solution 4:
Hopefully this helps:
>>> seta = set('1234')
>>> listb = ['a','b','c']
>>> seta.union(listb)
set(['a', 'c', 'b', '1', '3', '2', '4'])
>>> seta
set(['1', '3', '2', '4'])
>>> seta = seta.union(listb)
>>> seta
set(['a', 'c', 'b', '1', '3', '2', '4'])
Solution 5:
Please notice the function set.update()
. The documentation says:
Update a set with the union of itself and others.