3

Why does the below code returns an empty list when it should return [4, 3, 2] (because of the negative step size):

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)
Akshay J
  • 5,362
  • 13
  • 68
  • 105

2 Answers2

4

It starts counting from "2" going backwards (step -1) until "-5" is reached - but reaching the element "-5" would require positive step in this case.

For example the output of:

i[2::-1]

is: [2, 1, 0]

Lemurata
  • 235
  • 2
  • 12
0

As it turns out, when going from left to right (using negative or positive version of index), a positive step size is required.

Going from right to left requires a negative step size:

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]

# to get 6, 7, 8
print(i[6:9])
print(i[-4:-1:1])
print(i[6:-1:1])
print(i[-4:9:1])


# to get 8, 7, 6
print(i[8:5:-1])
print(i[-2:-5:-1])
print(i[-2:5:-1])
print(i[8:-5:-1])
Akshay J
  • 5,362
  • 13
  • 68
  • 105