How does the stride work in list slicing?


#1

Question

How does the stride work in list slicing?

Answer

When we want a slice of a list, we can specify the start, end, and stride. The stride is 1 by default and will go through each number in the range. If you change the number, then that’s by how many it’ll change each time. Take a look at the example below for a better understanding:

my_name = “BobbyTarantino”

print my_name[::1]  #BobbyTarantino
print my_name[::-1 ]#onitnaraTybboB

print my_name[::2]  #Bbyaatn
print my_name[::-2] #oinrTbo

FAQ: Learn Python - Advanced Topics in Python - List Slicing Syntax
#2
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]

With the above code, the start point is 2 and ends at 9 with a stride of 2 ( thats if am right)
But when run this code the outcome is as shown below

[9, 25, 49, 81]
[9, 25, 49, 81]
[9, 25, 49, 81]
[9, 25, 49, 81]
[9, 25, 49, 81]

Can someone help explain the logic and syntax flow for me Please!!!
Am a bit thrown off


#3

@iamstyles The reason it’s printing the result 5 times is probably because each check the SCT (Submission Correctness Test) makes re-runs your code. If you run it in a Python console locally, it’ll only print the list once.


#4

@iamstyles The default starting index is 0, that means it starts at index 2 inclusive which has a value of 9, it ends at index 9 exclusive (-> index 8 inclusive) which has a value of 81, with a stride of 2 which refer to index 4 and 6 having 25 and 49 as values. The result should normally be displayed in 1 line only.