The Python Oracle

Is it guaranteed that False "is 0" and True "is 1"?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Question
00:58 Accepted answer (Score 11)
01:42 Answer 2 (Score 4)
02:45 Thank you

--

Full question
https://stackoverflow.com/questions/1026...

Question links:
[Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?]: https://stackoverflow.com/questions/2764...

Accepted answer links:
[part of the language specification]: http://docs.python.org/reference/datamod...

Answer 2 links:
[Ignacio]: https://stackoverflow.com/a/10263976/577...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #boolean

#avk47



ACCEPTED ANSWER

Score 11


It is part of the language specification, so any Python implementation should implement the booleans as equivalent to the integers.

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.




ANSWER 2

Score 4


Yes -- this is guaranteed -- with the caveat that True and False may be reassigned; but that doesn't affect the results of boolean operations. (Thanks to Ignacio for the documentary proof.) In fact, back when there was no ternary operator, this was one of the methods used to emulate it. Nowadays, if you want a ternary operator, use the ternary operator. But sometimes this construct is still useful. For example:

>>> even_odd = [[], []]
>>> for i in range(10):
...     even_odd[i % 2 == 1].append(i)
... 
>>> print even_odd
[[0, 2, 4, 6, 8], [1, 3, 5, 7, 9]]

You can do this with a dictionary as well. It has a ternary operator equivalent...

>>> even, odd = [], []
>>> for i in range(10):
...     (even if i % 2 == 1 else odd).append(i)
... 
>>> even, odd
([1, 3, 5, 7, 9], [0, 2, 4, 6, 8])

But I actually find the list-indexing version easier to read, at least in this case. YYMV.