Strange behavior with python slicing

a[3:8:-1] instructs python to start from 3 and go to 8 by steps of -1

This creates an empty list: it's not possible to reach 8 from 3 by adding -1 (just like list(range(3,8,-1)) which gives an empty list too)

When you do a[:5:-1] then start is the default start, which python sets to "end of list" so it "works"

Same as when you do a[::-1] the start & stop are the default ones, and python understands that they're from end to start (else this notation wouldn't be useable)


With

a[3:8:-1]

The start and stop positions of the slice aren't adjusted based on the step. With a negative step, you're having it go backwards from 3, but there are no elements with indices in the range 3 to 8 counting back from 3, so you get an empty list.

You need to set the start and stop accordingly:

a[8:3:-1]

Which will count back from 8 to 4.

Tags:

Python

List

Slice