-1

When I try to initialize a set using the following statement:

myset = {['ki','ni']}

I am presented with the following error:

TypeError: unhashable type: 'list'

However, I can initialize the set with the same list with the set() function as follows:

myset = set(['ki','ni'])

I understand that the elements of a set have to be immutable and hence the error that I have specified in the first case, could be just due to that. What is confusing is that, why does this work when the set() function is used and not when directly initializing a set using the curly ({}) braces?

halfer
  • 19,824
  • 17
  • 99
  • 186
Kiran Hegde
  • 680
  • 4
  • 14
  • Your second code is equivalent to `{*['ki', 'ni']}`. It looks like `{'ki', 'ni'}`. `{*['ki','ni']} == set(['ki','ni'])` evaluates to `True`. Notice, the output is `{'ki', 'ni'}` not `{['ki', 'ni']}`. – Sayandip Dutta Jan 15 '20 at 11:56

2 Answers2

2

{['ki','ni']} means a set containing one element, ['ki','ni']. That's not a valid element for a set, so you get the error.

set(iterable) means a set containing all the items in iterable, i.e. what you would get if you iterated over iterable with a for loop. In this case it evaluates to {'ki','ni'}, a set containing two strings.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
1

Because your two code snippets do two different things.

The first one, {['ki','ni']}, tries to add the list itself to a set; which as you also observed fails since lists are not hashable.

The second one, set(['ki','ni']), succeeds as it converts a list to a set, aka adds the elements of the list to the set.

Ma0
  • 15,057
  • 4
  • 35
  • 65