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?

asked Jul 30, 2018 at 16:44
3
  • 3
    The first example should be a SyntaxError since you can't define a set that way. You can use either {} or set() to define a set. Commented Jul 30, 2018 at 16:47
  • Did you mean s = {['list']}. In python 3.6.0 your code gives a SyntaxError. But this gives the error you posted. Commented Jul 30, 2018 at 16:49
  • It was a typo. Corrected the same Commented Jul 30, 2018 at 17:03

2 Answers 2

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.

answered Jul 30, 2018 at 16:49
Sign up to request clarification or add additional context in comments.

1 Comment

It was a typo.Corrected the same.
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.

answered Jul 30, 2018 at 16:49

2 Comments

It was a typo.Corrected the same.
Yup! I edited the answer to reflect the edited question.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.