Add list to set

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')}

Leave a Comment