0
s={['list']}

Gives error as below:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
s=set(['list'])

However above works fine. Why?

Shubham S. Naik
  • 341
  • 1
  • 4
  • 14

2 Answers2

2

Your first example should be giving you a SyntaxError.

{['list']} is a set containing a list which raises an error because lists are not hashable.
set(['list']) is a set built from an iterable that happens to be a list. The equivalent expression using curly braces would be {'list'}, which works fine because strings are hashable.

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
1

The first example is not valid because lists are unhashable.

{['list']} is read as a set containing a single item of type list, but lists cannot be used as set items or keys in python, so you get an error.

The closest analogue would be to use a tuple {('list')}, since tuples are hashable, but it seems more likely that you just want the string, in which case you should write:

s = {'list'}

The second example is valid python syntax.

It calls the set constructor on a list of items to get a set of those items.

Ollin Boer Bohan
  • 2,296
  • 1
  • 8
  • 12