What happens here is a bit confusing, since [1,2,3][True] has two sets of [] , which are interpreted differently.
What happens is a little more clear if we split the code into several lines.
The first set [] creates a list object. Let this object be named a :
>>> [1,2,3] [1, 2, 3] >>> a = [1,2,3] >>>
The second set [] indicates the index inside this list. You usually see the code as follows:
>>> a[0] 1 >>> a[1] 2 >>>
But this is also true for using the list object directly, without specifying a name:
>>> [1,2,3][0] 1 >>> [1,2,3][1] 2
Finally, the fact that True and False can be used as indices is that they are treated as integers. From the data model documents :
There are three types of integers:
Ordinary integers ....
Long integers .....
Booleans
They represent true values โโFalse and True. Two objects representing the values โโFalse and True are the only Boolean objects. The Boolean type is a subtype of prime integers, and Boolean values โโbehave like the values โโ0 and 1, respectively, in almost all contexts, with the exception that when converting to a string, the string "False" or "True" is returned, respectively.
Thus, [1,2,3][True] equivalent to [1,2,3][1]