What's happening here is a little confusing, since [1,2,3][True]
has two sets of []
s that are being interpreted in different ways.
What's going on is a little more clear if we split the code over a few lines.
The first set of []
s construct a list object. Let's assign that object the name a
:
>>> [1,2,3]
[1, 2, 3]
>>> a = [1,2,3]
>>>
The second set of []
specify an index inside that list. You'd usually see code like this:
>>> a[0]
1
>>> a[1]
2
>>>
But it's just as valid to use the list object directly, without ever giving it a name:
>>> [1,2,3][0]
1
>>> [1,2,3][1]
2
Lastly, the fact that True
and False
are useable as indexes is because they're treated as integers. From the data model docs:
There are three types of integers:
Plain integers....
Long integers.....
Booleans
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 plain integers, 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.
Thus, [1,2,3][True]
is equivalent to [1,2,3][1]