0

There is this code:

a = [1, 2, 3, 4, 5]
a[2:4:-1] # returns []
a[4:2:-1] # returns [5, 4]

Why statement a[2:4:-1] returns an empty list altough the range is specified?

Saullo G. P. Castro
  • 53,388
  • 26
  • 170
  • 232
scdmb
  • 14,431
  • 20
  • 79
  • 125
  • What specific non-empty output did you expect? – lvc May 26 '13 at 09:58
  • @jamylak none of the answers to that question discuss this situation. A few talk about `a[::-1]` reversing a list, but only gives any examples like this one (where start and end are both given, and step is negative), and another gives the (AFAICT, misleading) 'using a negative step reverses the interpretation of `start` and `end`' (`a[4:2:-1]` contains the value at index 4 and not the one at index 2, as expected under non-reversed interpretation). – lvc May 26 '13 at 10:08
  • @lvc however they give a very detailed explanation on slicing – jamylak May 26 '13 at 10:09

1 Answers1

7

If you attempt to use a[2:4:-1] you try to go backward from list index 2 to 4 which will obviously not work.

George
  • 576
  • 1
  • 4
  • 14