pythonlistboolean

Why do x[False] and x[True] for Python lists work?


If I have x as the list of items, why does x[True] or x[False] modify 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']

Why does this code work?


Solution

  • 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'}