list1 = [1, 2, 3, 4]
element = list1[1:][1]
print(element)
Why does it print 3?
How is this evaluated? Does it first take the elements of list1 that are from index 1: then it takes the 1 index of that?
list1 = [1, 2, 3, 4]
element = list1[1:][1]
print(element)
Why does it print 3?
How is this evaluated? Does it first take the elements of list1 that are from index 1: then it takes the 1 index of that?
Python's grammar specifies how it is evaluated, since it constructs a syntax tree of your program.
Without going much into technical detail, such indexing is left recursive. This means that:
foo[bar][qux]
is short for:
(foo[bar])[qux]
so such indices are evaluated left-to-right.
It is evaluated like:
list1 = [1, 2, 3, 4]
temp = list1[1:] # create a sublist starting from the second item (index is 1)
element = temp[1] # obtain the second item of temp (index is 1)
(of course in reality, no temp
variable is created, but the list itself is a real object stored in memory, and thus also might change state, etc.).
So first we slice starting from the second item, this results in a list [2, 3, 4]
, and then we obtain the second item of that list, so 3
.