0

I'm slicing lists in python and can't explain some results. Both of the following seem natural to me:

>>>[0,1,2,3,4,5][1:4:1]
[1, 2, 3]

>>>[0,1,2,3,4,5]
[::-1] == [5,4,3,2,1,0]

However,

>>>[0,1,2,3,4,5][1:4:-1]
[]

thought I expected it to be [3,2,1]. Why does it produce [ ]? Why does it not reverse the list? What happens first inside python, the step or the slicing?

I also found that

>>>[0,1,2,3,4,5][-3:-6:-1]
[3,2,1]
mark mark
  • 306
  • 2
  • 13
  • 2
    Possible duplicate of [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – John Coleman Jul 09 '19 at 20:07
  • 1
    The intuition I use for this is that in thinking of `[start:stop:step]`, both `[start:stop]` and `step` must be in the same direction. The same way you can't, while counting out loud, count starting at 1 and ending at 5 by counting backwards – G. Anderson Jul 09 '19 at 20:12
  • Duplicate: [Reversing a list slice in python](https://stackoverflow.com/questions/34085912/reversing-a-list-slice-in-python) – Georgy Dec 03 '19 at 09:39

2 Answers2

0

The third number in the slice is the step count. So, in [0,1,2,3,4,5][1:4:-1], the slicing starts at 1 and goes DOWN by 1 until it is less than 4, which is immediately is. Try doing this:

>>> [0,1,2,3,4,5][4:1:-1]
[4, 3, 2]
brandonwang
  • 1,603
  • 10
  • 17
0

If you are slicing this then slicing will look like this [start:end:step]. For this one:

>>> [0,1,2,3,4,5][1:4:1]
[1, 2, 3]

It is staring from index 1 to index 3 because it exlcudes the index 4 with 1 step at a time. You are getting an empty list in the second one because you are stepping -1 from 1st index. So this will be the solution.

>>> [0,1,2,3,4,5][4:1:-1]
[4, 3, 2]

This works because you are taking an index from 4 to one with -1 step forward.

Dan D.
  • 73,243
  • 15
  • 104
  • 123