Reputation: 6782
I have a custom list like this :
mylist1= [-2,0,1,1.5,2,3,6,8,5,'a','-%3','A',True,False,list(),tuple(),dict()]
Here I have most of the datatypes in this list,so I just tried to sort them and see how it sorts all them.
And It gave me output like this:
print sorted(mylist1)
[-2, 0, False, 1, True, 1.5, 2, 3, 5, 6, 8, {}, [], '-%3', 'A', 'a', ()]
Here we can see {}
is placed before [] and ()
at the most end.
All I searched and got __cmp__
is running inside this mergesort.
More info
I have two questions:
I just want to know how this precedence of values with the different datatypes is defined in python
If I include set()
in above mylist, it won't run this sort. why so? it is showing TypeError: can only compare to a set
Upvotes: 0
Views: 52
Reputation: 19677
According to the Python2.7 tutorial:
Note that comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types are ordered by their name. Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc. Mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc.
Sets are only comparable between each others, so <
can be used to compare super/sub-sets:
In addition, both Set and ImmutableSet support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).
All these inconsistency explain why you should use Python 3 instead of Python 2.
Using Python 3, only compatible types are comparable.
Upvotes: 2