arrays - Python list - True/False first two elements? -


following trial , error after posting this question, observe following phenomena:

>>> [1,2][true] 2 >>>>[1,2][false] 1 >>>>[1,2,3][true] 2 

if add third or subsequent element, has no effect.

can point me explanation of these observations? presume general property relating first 2 elements in python list?

thanks

what's happening here little confusing, since [1,2,3][true] has 2 sets of []s being interpreted in different ways.

what's going on little more clear if split code on few lines.

the first set of []s construct list object. let's assign object name a:

>>> [1,2,3] [1, 2, 3] >>> = [1,2,3] >>> 

the second set of [] specify index inside list. you'd see code this:

>>> a[0] 1 >>> a[1] 2 >>> 

but it's valid use list object directly, without ever giving name:

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

lastly, fact true , false useable indexes because they're treated integers. data model docs:

there 3 types of integers:

plain integers....

long integers.....

booleans

these represent truth values false , true. 2 objects representing values false , true boolean objects. boolean type subtype of plain integers, , boolean values behave values 0 , 1, respectively, in contexts, exception being when converted string, strings "false" or "true" returned, respectively.

thus, [1,2,3][true] equivalent [1,2,3][1]


Comments