22

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 ?

Kara
  • 6,115
  • 16
  • 50
  • 57
James Sapam
  • 16,036
  • 12
  • 50
  • 73

1 Answers1

42

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thank you so much, would you mind putting some link or any official docs. – James Sapam Feb 26 '14 at 12:04
  • 2
    @yopy: There is no reference to this in the documentation, I think. I always look to the source code. I'll add some references. – Martijn Pieters Feb 26 '14 at 12:06
  • Except when `None` isn't sorted first like in http://bugs.python.org/issue1673405 which was rejected. (And a recent python-dev thread pointed out that the specification never actually had a "None gets sorted first" rule, even though it *usually* is in cPython 2). – Wooble Feb 26 '14 at 12:06
  • @Wooble: It's not documented, so any implementation is free to invent their own order. – Martijn Pieters Feb 26 '14 at 12:14