Skip to content

Instantly share code, notes, and snippets.

@y56
Created February 14, 2020 01:24
Show Gist options
  • Save y56/c3ad5631a6bf45ce4037575ff4819861 to your computer and use it in GitHub Desktop.
Save y56/c3ad5631a6bf45ce4037575ff4819861 to your computer and use it in GitHub Desktop.
Python: Add list to set
https://stackoverflow.com/questions/1306631/python-add-list-to-set
Python: Add list to set?
Ask Question
Asked 10 years, 5 months ago
Active 1 year ago
Viewed 276k times
220
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.
python list set
shareedit
edited Feb 25 '11 at 19:25
asked Aug 20 '09 at 14:35
Adam Matan
90.1k108108 gold badges298298 silver badges464464 bronze badges
2
Do you want to add the list to the set or the items in the list? – pkit Aug 20 '09 at 14:39
The list itself - I want to have a set of lists. – Adam Matan Aug 20 '09 at 14:41
Then use the tuple option that Otto answered. – pkit Aug 20 '09 at 14:43
add a comment
12 Answers
active
oldest
votes
173
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.
shareedit
edited May 23 '17 at 12:18
Community♦
111 silver badge
answered Aug 20 '09 at 14:39
Otto Allmendinger
22.4k55 gold badges5757 silver badges7777 bronze badges
6
And if you ever want to add a set to a set, use frozenset. – FogleBird Aug 20 '09 at 14:46
4
collections.namedtuple might be considered "official" counterpart of the dict. – SilentGhost Aug 20 '09 at 15:28
1
@Wahnfrieden: that is adding the contents of a set, not the set itself. – Otto Allmendinger Aug 20 '09 at 21:49
Well answered. The tuple() function is also worth mentioning. – Adam Matan Aug 22 '09 at 11:14
Please check the second anwers – Andrej Gajduk Jun 11 '15 at 9:51
show 3 more comments
527
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.
shareedit
edited Jan 17 '19 at 2:05
Boris
2,90544 gold badges2727 silver badges4040 bronze badges
answered Aug 20 '09 at 14:41
aehlke
10.8k44 gold badges3030 silver badges4242 bronze badges
set.update() adds the list to the set, correct? what is the pipe equals operator for? – FistOfFury Jan 7 at 18:24
add a comment
71
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.
shareedit
edited May 23 '17 at 12:02
Community♦
111 silver badge
answered May 2 '17 at 20:01
JDiMatteo
6,79122 gold badges3535 silver badges5252 bronze badges
Works like charm – Indra Feb 4 '19 at 12:15
add a comment
40
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'])
shareedit
answered Aug 23 '13 at 9:24
alvas
77.4k7676 gold badges296296 silver badges539539 bronze badges
add a comment
15
Please notice the function set.update(). The documentation says:
Update a set with the union of itself and others.
shareedit
edited Oct 20 '12 at 21:44
the Tin Man
143k2929 gold badges188188 silver badges267267 bronze badges
answered May 5 '12 at 12:01
eggfly
15111 silver badge22 bronze badges
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
add a comment
8
list objects are unhashable. you might want to turn them in to tuples though.
shareedit
answered Aug 20 '09 at 14:43
SilentGhost
228k5151 gold badges279279 silver badges275275 bronze badges
add a comment
5
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.
shareedit
edited Aug 20 '09 at 15:16
answered Aug 20 '09 at 14:47
user135331
21111 silver badge55 bronze badges
add a comment
4
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.
shareedit
edited Aug 20 '09 at 16:54
answered Aug 20 '09 at 14:47
hughdbrown
37.8k2020 gold badges7878 silver badges101101 bronze badges
add a comment
3
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.
shareedit
answered Mar 23 '11 at 17:33
Dunes
27.9k77 gold badges5757 silver badges7676 bronze badges
add a comment
3
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')])
shareedit
answered Aug 20 '09 at 14:45
Noah
13.4k66 gold badges5252 silver badges6464 bronze badges
add a comment
2
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
shareedit
answered Feb 19 '14 at 7:26
kashif
41444 silver badges99 bronze badges
add a comment
-4
This should do:
set(tuple(i) for i in L)
shareedit
edited Aug 25 '17 at 14:24
Ivan
6,57133 gold badges1818 silver badges5050 bronze badges
answered Aug 25 '17 at 7:26
WQS
111 bronze badge
add a comment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment