14

Is the ordering of True and False well defined in Python, or is it left as an implementation detail?

From the console, I'm seeing False sort before True...but I don't know if that's a behavior I should rely on or not.

(I'm sure there's some Python doc about this, but I can't find it...)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Richard Levasseur
  • 14,562
  • 6
  • 50
  • 63

2 Answers2

25

http://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy

Booleans: These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

This reads to me that the python language requires False < True, False == 0, True == 1, True != 2.

The same wording is retained in Python 3 as well.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • 2
    If you're unsure you agree with sharth's understanding, try plugging it into an interpreter. You'll quickly verify that `False < True`. In fact, reading the spec and playing around with it into the interpreter are always good ideas! – rsegal Nov 13 '12 at 00:27
  • It's worth noting that 'sorting is defined' basically means comparisons are defined, which means that if something is less than something else, it will be sorted correctly and as noted here `False < True`. – Grismar Dec 02 '19 at 00:08
1

We can show bool is sortable using the Python REPL, with False being the lower value:

>>> sorted([False, True, True, False, True])
[False, False, True, True, True]
Graham Lea
  • 5,797
  • 3
  • 40
  • 55