296

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.

Paulo Boaventura
  • 1,032
  • 1
  • 7
  • 25
Adam Matan
  • 107,447
  • 124
  • 346
  • 512
  • 5
    Do you want to add the list to the set or the items in the list? – pkit Aug 20 '09 at 14:39
  • 1
    The list itself - I want to have a set of lists. – Adam Matan Aug 20 '09 at 14:41
  • 1
    Seems 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. Apr 11 '20 at 15:09

12 Answers12

706

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.

Boris
  • 7,044
  • 6
  • 62
  • 63
aehlke
  • 13,075
  • 5
  • 32
  • 43
  • set.update() adds the list to the set, correct? what is the pipe equals operator for? – FistOfFury Jan 07 '20 at 18:24
  • 1
    With respect to sets, the `|` operator implements the [set union operation](https://en.wikipedia.org/wiki/Union_(set_theory)). 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). `` – Cecil Curry Apr 27 '20 at 05:16
232

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: use tuple instead
    • set: use frozenset 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.
Community
  • 1
  • 1
Otto Allmendinger
  • 25,140
  • 7
  • 64
  • 79
89

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.

Community
  • 1
  • 1
JDiMatteo
  • 9,062
  • 3
  • 47
  • 55
45

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'])
alvas
  • 94,813
  • 90
  • 365
  • 641
16

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

Update a set with the union of itself and others.

the Tin Man
  • 150,910
  • 39
  • 198
  • 279
eggfly
  • 161
  • 1
  • 2
  • 5
    This doesn't answer the question (since the OP wants to add the list itself to the set) but it was the answer that I needed when Google brought me here :-) – tom stratton Mar 26 '13 at 16:48
  • 1
    Well, it seems like the most relevant answer to the question to me... for instance, if b = set([1]), b.update([7,25]) will give b the following value : set([1, 25, 7]) ---> Isn't it what we're looking for here? – Louis LC Oct 19 '14 at 22:16
9

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

SilentGhost
  • 264,945
  • 58
  • 291
  • 279
7

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.

user135331
  • 229
  • 1
  • 5
6

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.

Dunes
  • 32,114
  • 7
  • 68
  • 83
5

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.

hughdbrown
  • 42,826
  • 20
  • 80
  • 102
4

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')])
Noah
  • 17,200
  • 7
  • 59
  • 68
3

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
kashif
  • 454
  • 4
  • 9
1

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'}
U11-Forward
  • 41,703
  • 9
  • 50
  • 73
  • Seems like OP needs to create a set of lists. Your solution would create a set of elements. I don't think they're they same things. In your example, if `l` was equal to `['f', 'g', 'a']`, unpacking `l` would lose an `a`. – a3y3 Jan 03 '21 at 17:12