How do I add a list of values to an existing set?
-
7Do you want to add the list to the set or the items in the list?pkit– pkit2009-08-20 14:39:37 +00:00Commented Aug 20, 2009 at 14:39
-
1The list itself - I want to have a set of lists.Adam Matan– Adam Matan2009-08-20 14:41:37 +00:00Commented Aug 20, 2009 at 14:41
-
2Seems the best-suited answer is the underrated one, suggesting using aSet.add(id(lst)) before adding lst itself to some list/queue/etc, to be sure that you did it ones. You should reconsider the accepted answer.Rustam A.– Rustam A.2020-04-11 15:09:57 +00:00Commented Apr 11, 2020 at 15:09
13 Answers
Adding the contents of a list
Use set.update() or the |= operator:
>>> a = set('abc')
>>> a
{'a', 'b', 'c'}
>>> xs = ['d', 'e']
>>> a.update(xs)
>>> a
{'e', 'b', 'c', 'd', 'a'}
>>> xs = ['f', 'g']
>>> a |= set(xs)
>>> a
{'e', 'b', 'f', 'c', 'd', 'g', 'a'}
Adding the list itself
It is not possible to directly add the list itself to the set, since set elements must be hashable.
Instead, one may convert the list to a tuple first:
>>> a = {('a', 'b', 'c')}
>>> xs = ['d', 'e']
>>> a.add(tuple(xs))
>>> a
{('a', 'b', 'c'), ('d', 'e')}
2 Comments
| operator implements the set union operation. Both the |= operator and set.update() method apply that operation in-place and are effectively synonymous. So, set_a |= set_b could be considered syntactic sugar for both set_a.update(set_b) and set_a = set_a | set_b (except that in the latter case, the same set_a object is reused rather than reassigned). </ahem>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: usetupleinsteadset: usefrozensetinsteaddict: 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.
5 Comments
collections.namedtuple might be considered "official" counterpart of the dict.OrdereDict works for the dict case? From the collections lib?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.
Comments
Please notice the function set.update(). The documentation says:
Update a set with the union of itself and others.
2 Comments
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.
Comments
I 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 than hash. As such I found mydict[id(mylist)] = mylist instead of myset.add(mylist) to offer the behaviour I wanted.
Comments
You want to add a tuple, not a list:
>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> t = tuple(l)
>>> t
('f', 'g')
>>> a.add(t)
>>> a
set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])
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.
Comments
Try using * unpack, like below:
>>> a=set('abcde')
>>> a
{'a', 'd', 'e', 'b', 'c'}
>>> l=['f','g']
>>> l
['f', 'g']
>>> {*l, *a}
{'a', 'd', 'e', 'f', 'b', 'g', 'c'}
>>>
Non Editor version:
a=set('abcde')
l=['f', 'g']
print({*l, *a})
Output:
{'a', 'd', 'e', 'f', 'b', 'g', 'c'}
1 Comment
l was equal to ['f', 'g', 'a'], unpacking l would lose an a.