Reputation: 1247
I know that this is a commonly asked question and there are numerous posts discussing the topic surrounding hash-able property of set elements, but I am trying to understand why set can accept 1D list but not multi-dimensional list to initialize it.
Look at the below code: Case1, Case2 works (they accept 1D list) while Case3 does not (it accepts 2D list). How and what is the role of dimension in set initialization.
#Case1:
cities = set(["Frankfurt", "Basel","Freiburg"])
print(cities)
#Case2:
citylist = list(["Frankfurt", "Basel","Freiburg"])
setofcitites = set(citylist)
print(setofcitites)
#Case3:
more_cities = set([["Frankfurt", "Basel","Freiburg"], ["Dubai", "Toronto","Sydney"]])
print(more_cities)
Upvotes: 0
Views: 497
Reputation: 164823
Short answer
Strings are hashable, but lists are not.
Longer answer
Understand precisely what is being hashed when you use the set
function.
In Case 1 and Case 2, you are hashing the elements of the list, which are actually strings.
In Case 3, you are hashing the elements of the list, which are lists themselves.
Since lists are mutable objects, they are not hashable.
Upvotes: 2
Reputation: 25829
That's because in the first two cases you're essentially converting a list into a set i.e. individual elements of the list become elements of the set. Since those are strings, and strings are hashable, they are allowed in the set.
In the third case the elements of the list you're trying to convert into a set are lists themselves and a list is not hashable, hence the error. It's equivalent as if you've tried to do:
your_set = set()
your_set.add("Frankfurt") # OK
your_set.add(["Frankfurt", "Basel"]) # Err
Upvotes: 1
Reputation: 4983
list is mutable object, thus can't be hashed
this will work
more_cities = set([("Frankfurt", "Basel","Freiburg"), ("Dubai", "Toronto","Sydney")])
Upvotes: 0
Reputation: 45826
In case 1 and 2, no lists are being hashed. The list is iterated, and it's elements are hashed. The hashed elements aren't lists, and are otherwise hashable, so it's fine.
In case 3 though, the outer list is iterated like before, but each element of the list is another list, which are attempted to be hashed. As you know, that won't end well.
Upvotes: 1