2

If I have x as the list of items, why does the x[True] or x[False] modifies the first or second elements of the list?

Please see code sample below:

x = [1, 2]
x[True] = 'a'
x[False] = 'b'
print(x) # --> ['a', 'b']

Please give explanation why this code works?

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82

1 Answers1

4

Since x is the list the passed index is being converted to the integer representation. The integer representation of the True and False are 1 and 0 respectively. As result it leads to the modification of the first and second elements in the list. From the Python Data model documentation:

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 the integer type, 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.

In addition to the sample with the list that causes interesting behaviour for the dictionary:

x = {}
x[True] = 'a'
print(x) # --> {True: 'a'}
x[1] = 'b' 
print(x) # --> {True: 'b'} and not {True: 'a', 1: 'b'}
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82