Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, None evaluates to less than zero? [duplicate]

In Python, None evaluates to less than zero?

ActivePython 2.7.2.5 (ActiveState Software Inc.) based on Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> None < 0 True >>> None == 0 False >>> None > 0 False >>> 

Is this expected?

I would have guessed that None would either be equal to zero (through type coercion), or that all of these statements would return False.

like image 559
Mike M. Lin Avatar asked Sep 12 '11 05:09

Mike M. Lin


People also ask

Is None less than 0 Python?

As the null in Python, None is not defined to be 0 or any other value. In Python, None is an object and a first-class citizen!

What does None evaluate to in Python?

In Python, None represents an absence of a value in a variable. In Python, None is what would be a null in other commonly used programming languages. Unlike the null in the other languages, Python's None has nothing to do with values 0 or False for example.

Does None evaluate to true in Python?

However, None evaluates to False, so the or operator returns the first "True" value, which is the second value. We have to modify the code so that both the or arguments are True.

What is None equal to in Python?

Introduction to the Python None value It means that Python creates one and only one None object at runtime. It's a good practice to use the is or is not operator to compare a value with None . Note that you cannot override the is operator behavior like you do with the equality operator ( == ).


2 Answers

See the manual:

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result).

and

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

like image 59
ThiefMaster Avatar answered Sep 19 '22 15:09

ThiefMaster


From the docs:

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

NoneType compares as smaller than int since the comparison appears to be case-sensitive.

>>> type(0) <type 'int'> >>> type(None) <type 'NoneType'> >>> 'NoneType' < 'int' True 
like image 31
hammar Avatar answered Sep 23 '22 15:09

hammar