+5 votes
in Programming Languages by (22.6k 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

+1 vote
by (41.9k points)

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}