3
In [1]: a=5

In [2]: print(["is odd", "is even"][a % 2 == 0])
is odd

In [3]: [a%2 == 0]
Out[3]: [False]

What I understood is a % 2 == 0 evaluates to True or False.

So if it is True then that is equivalent to 1 and using list indices it's going to print 'is even'.

I've read this and came to know bool is an instance of int.

So when used as in index bool evaluates to it's equivalent number i.e 0 or 1.

My question

Based on intuition we can know whether it's going to be an int or bool

But how does Python know? Does it have any criteria when to use as bool and when to use as int? Anything from Python3 documentation would be appreiated.

Community
  • 1
  • 1
Ajay
  • 5,267
  • 2
  • 23
  • 30

2 Answers2

6

In Python 2.x this is not guaranteed as it is possible for True and False to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.

In Python 3.x True and False are keywords and will always be equal to 1 and 0.

Under normal circumstances in Python 2, and always in Python 3:

False object is of type bool which is a subclass of int:

 object
   |
  int
   |
  bool

It is the only reason why in your example, ['zero', 'one'][False] does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define the __index__ method (thanks mark-dickinson).

Edit:

It is true of the current Python version, and of that of Python 3. The docs for Python 2.6 and the docs for Python 3 both say:

There are two types of integers: [...] Integers (int) [...] Booleans (bool) and in the boolean subsection:

Booleans: These represent the truth values False and True [...] 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.

So booleans are explicitly considered as integers in Python 2.6 and 3.

bagrat
  • 7,158
  • 6
  • 29
  • 47
jayprakashstar
  • 395
  • 2
  • 12
0

The bool instances, True and False, are separate from the int instances, 0 and 1. The thing is that the bools behave like integers in many contexts. Such as True+True which is 2. However if we check if they are the same object we see it is not: True is 1. On the other hand it is true that True is True. Here's an example which behaves like integers but are printed as True and False and compares differently with is.

class Bool(int):
    def __repr__(self):
        return 'True' if self==1 else 'False'

https://docs.python.org/3/library/stdtypes.html#bltin-boolean-values

Ariakenom
  • 204
  • 1
  • 5