Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list - True/False first two elements? [duplicate]

Following some trial and error after posting this question, I observe the following phenomena:

>>> [1,2][True]
2
>>>>[1,2][False]
1
>>>>[1,2,3][True]
2

If I add a third or subsequent element, it has no effect.

Can someone point me to the an explanation of these observations? I presume this is some general property relating to the first two elements in any Python list?

Thanks

like image 208
Pyderman Avatar asked Jul 19 '13 09:07

Pyderman


2 Answers

Because:

>>> True == 1
True
>>> False == 0
True

Boolean is a subclass of int. It is safe* to say that True == 1 and False == 0. Thus, your code is identical to:

>>> [1, 2][1]
2
>>> [1, 2][0]
1
>>> [1, 2, 3][1]
2

That's why when you add more elements, the output will remain the same. It has nothing to do with the length of the list, because it is just basic indexing affecting only the first two values.


*: NB: True and False can actually be overritten in Python <=2.7. Observe:

>>> True = 4
>>> False = 5
>>> print True
4
>>> print False
5

*: However, since Python 3, True and False are now keywords. Trying to reproduce the code above will return:

>>> True = 4
  File "<stdin>", line 1
SyntaxError: assignment to keyword
like image 183
TerryA Avatar answered Nov 01 '22 08:11

TerryA


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]

like image 31
James Polley Avatar answered Nov 01 '22 09:11

James Polley