0

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:

Question1:

I just want to know how this precedence of values with the different datatypes is defined in python

Question2:

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

4
  • Why Down Vote?? I have asked a valid question after searching many things. If you know the answers please post it instead of downvoting Commented Mar 25, 2017 at 9:17
  • Don't ask multiple questions at once. And if you research, you find existing answers, e.g. stackoverflow.com/questions/3270680/… and 2, stackoverflow.com/questions/4084243/… Commented Mar 25, 2017 at 9:18
  • @jonrsharpe Thanks, but this were related questions of same list , so I asked. Commented Mar 25, 2017 at 9:21
  • I'm not sure what you're trying to say. Both of your questions are answered elsewhere; the second in particular is easy to find answers for, as you have an error message to search for. That's not a good reason to ask again. Commented Mar 25, 2017 at 9:28

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.