In some corners of StackOverflow, it is well-known that you cannot convert a list into a set, because it is "unhashable". In other corners, it is well-known that you can convert a list into a set. Where is the discrepancy?
Asked
Active
Viewed 503 times
-2
-
2You can convert a list to a set. You can't put a list *in* a set. – chepner Sep 19 '19 at 14:23
-
Understanding that a `set` expects an *iterable* is enough. In the second case the elements of the iterable are integers, whereas in the first they are lists, which are not hashable – yatu Sep 19 '19 at 14:25
1 Answers
1
The discrepancy comes from using a nested list, i.e. [[<a>, <b>, <c>]]
.
Set()
can handle a single-layer list; it treats every element of a list as an argument in the set constructor—but when nesting lists, it receives the inner list as a single argument. It then wants to make a set with a single element, containing the inner list. Because that inner list is still a list (it's not broken apart, as a single-layer list would be), it's unhashable, as described in the excellent answer here.

PProteus
- 549
- 1
- 10
- 23