1

Why is it possible to use boolean values as index in python? e.g

>>> a = [1, 2, 3, 4, 5]
>>> a[True]
2
>>> a[False]
1

Since python is a strongly typed language, shouldn't the compiler throw a TypeError just like when adding a string and integer together? e.g.

>>> "1" + 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: cant convert 'int' object to 'str' implicitly
>>> 1 + "1"
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Salailah
  • 435
  • 7
  • 12

1 Answers1

0

bool is actually a subclass of int. Just as every number is a boolean, every boolean is an integer. If you use int(True), you'll get 1 and if you do int(False), you'll get 0. When you use a[True], it's the same thing as a[1]. You know that bool subclasses int from this test:

>>> issubclass(bool, int)
True
zondo
  • 19,901
  • 8
  • 44
  • 83