This question already has an answer here:
-
Is everything greater than None? [duplicate]
2 answers
What I learnt from python None :
None is frequently used to represent the absence of a value
When i put in a list and sorted with numbers and string. I got the following result, which means it is the smallest number ?
Reverse:
>>> sorted([1, 2, None, 4.5, (-sys.maxint - 1), (sys.maxint - 1), 'abc'], reverse=True)
['abc', 9223372036854775806, 4.5, 2, 1, -9223372036854775808, None]
>>>
Normal sort:
>>> sorted([1, 2, None, 4.5, (-sys.maxint - 1), (sys.maxint - 1), 'abc'])
[None, -9223372036854775808, 1, 2, 4.5, 9223372036854775806, 'abc']
>>>
How python sorted function is working with None ?
When comparing different types, CPython 2 applies some different rules:
None
is sorted first.
- Numbers come before other types, and are compared numerically among themselves.
- Other types are ordered by their type name, unless they explicitly implement comparison methods.
In addition, some types implement custom sorting rules and can refuse all attempts to sort. Complex numbers raise an exception when you try to order them, for example, and datetime
objects do so when you try to order them relative to other types.
This isn't documented in the Python reference documentation; see the default comparison code in object.c
instead. It is an implementation detail and not something your code should ever rely on. The comparison operators documentation states:
Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.
The goal was to make comparisons between different types stable when sorting a sequence of mixed objects.
In Python 3, comparison rules have been tightened up; you can only compare objects that explicitly implement comparisons. After years of experience the conclusion was drawn that allowing for arbitrary comparisons was only leading to more confusion; comparing strings with digits in them with integers always confuses newcomers, for example.
Your code would raise an exception instead.