I'm confuse about how Python-3 performs list to set conversion in inconsistent way. When an input list is sorted in descending order, it creates a set in ascending order. When an input list is unsorted, it does nothing and the result set is unsorted. In one case, even unsorted list gets converted to a sorted set.
# list is unsorted and resulting set is unsorted
lst1 = [9,100,1]
thisset1 = set(lst1)
print(thisset1) # 9,100,1
# list is sorted in descending order and
# resulting set is sorted in ascending order
lst2 = [4,3,2,1]
thisset2 = set(lst2)
print(thisset2) # 1,2,3,4
# list is sorted in descending order and
# resulting set is sorted in ascending order
lst4 = [500,400,200]
thisset4 = set(lst4)
print(thisset4) # 500,400,200
# list is unsorted but resulting set is SORTED in ascending order
lst3 = [4,1,3,2]
thisset3 = set(lst3)
print(thisset3)
Is it because of hashing?
CodePudding user response:
A set is an unordered data structure. So order is random. Let's take an example u you used.
lst4 = [500,400,200]
set(lst4)
{400, 500, 200}
Which is different from yours. So order may be different for same input.