Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: 2 Index Location Brackets for a List

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?

like image 747
Emma Pascoe Avatar asked Sep 11 '26 19:09

Emma Pascoe


1 Answers

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.

like image 104
Willem Van Onsem Avatar answered Sep 14 '26 09:09

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!