Python – List slices with negative steps

List slices with negative steps… here is a solution to the problem.

List slices with negative steps

Why does the following code return an empty list when [4, 3, 2] should be returned (because the step size is negative):

i = [  0,  1,  2,  3,  4,  5,  6,  7,  8,  9]
   #[  0,  1,  2,  3,  4,  5,  6,  7,  8,  9]
   #[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]
s = i[2:-5:-1]
print(s)

Solution

It counts backwards from “2” (step -1) until it reaches “-5” – but in this case a forward step is required to reach the element “-5”.

For example, output:

i[2::-1]

Be:
[2, 1, 0]

Related Problems and Solutions