Why None is the smallest in python? [duplicate]
Asked Answered
H

1

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 ?

Hostetter answered 26/2, 2014 at 12:0 Comment(1)
#2214694Clownery
M
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.

Macilroy answered 26/2, 2014 at 12:2 Comment(4)
Thank you so much, would you mind putting some link or any official docs.Hostetter
@yopy: There is no reference to this in the documentation, I think. I always look to the source code. I'll add some references.Macilroy
Except when None isn't sorted first like in 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).Wellintentioned
@Wooble: It's not documented, so any implementation is free to invent their own order.Macilroy

© 2022 - 2024 — McMap. All rights reserved.