Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 224
Adam Matan Avatar asked Aug 20 '09 14:08

Adam Matan


People also ask

Can I add a list to a set?

You cannot add a list to a set. A set is an unordered collection of distinct hashable objects.

How do you add a list to a set in Python?

To add a list to set in Python, use the set. update() function. The set. update() is a built-in Python function that accepts a single element or multiple iterable sequences as arguments and adds that to the set.

How do you add all elements of a list into a set?

Add all items in list to set using add() & for loop. Iterate over all the items in the list using a for loop and pass each item as an argument to the add() function. If that item is not already present in the set, then it will be added to the set i.e.


1 Answers

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.

like image 95
aehlke Avatar answered Oct 19 '22 14:10

aehlke