7. list slicing syntax


#1

Hey! Although I do not have any errors (the code was already written in a chapter) I don't understand how it works.

l = [i ** 2 for i in range(1, 11)]

Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

print l[2:9:2]

Why actually 2:9:2 prints out these numbers [9, 25, 49, 81]?

Can anyone explain it to me?


#2

l[2:9:2] means a list with every second element of l from index 2(inclusive) to index 9 (exlusive).

The first number in the brackets is the start index, the second is the index oft he first element that's not included and the third number is the size of the "steps" that will be made.

You can use l[start:end] then the third number will be assumed to be 1.
print l[2:9] would print [9, 16, 25, 36, 49, 64, 81] but if we only take the first number than step over one and so on
we get [9, 25, 49, 81]


#3

Thanks a lot! Now i get it!