[python] Add list to set?

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.

This question is related to python list python-2.7 set

The answer is


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.


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

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.


Please notice the function set.update(). The documentation says:

Update a set with the union of itself and others.


You'll want to use tuples, which are hashable (you can't hash a mutable object like a list).

>>> a = set("abcde")
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> t = ('f', 'g')
>>> a.add(t)
>>> a
set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])

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.


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.


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

Here is how I usually do it:

def add_list_to_set(my_list, my_set):
    [my_set.add(each) for each in my_list]
return my_set

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.


list objects are unhashable. you might want to turn them in to tuples though.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict

Examples related to set

java, get set methods golang why don't we have a set datastructure Simplest way to merge ES6 Maps/Sets? Swift Set to Array JavaScript Array to Set How to sort a HashSet? Python Set Comprehension How to get first item from a java.util.Set? Getting the difference between two sets Python convert set to string and vice versa