+5 votes
in Programming Languages by (74.2k points)

I am trying to add a list to a set using add() function, but it's giving an error - "TypeError: unhashable type: 'list'".

Which Python function should I use?

>>> a=set()

>>> b=[1,2,3]

>>> a.add(b)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: unhashable type: 'list'

1 Answer

+2 votes
by (349k points)
selected by
 
Best answer

If you have to add one element to a set, you can use the add() function. But if you have to add a list to a set, you have to use the update() function.

Here is an example:

>>> a=set()
>>> b=[1,2,3]
>>> a.update(b)
>>> a
{1, 2, 3}
>>> a.add(4)
>>> a
{1, 2, 3, 4}
>>>


...