Python list - True / False first two elements?

After 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 an explanation of these observations? I assume this is some general property related to the first two elements in any Python list?

thanks

+6
source share
2 answers

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]

+12
source

Because:

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

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

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

Therefore, when you add more elements, the output will remain the same. This 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 overwritten in Python <= 2.7. Please note: sub>

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

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

 >>> True = 4 File "<stdin>", line 1 SyntaxError: assignment to keyword 
+27
source

Source: https://habr.com/ru/post/949812/


All Articles