Reyha24 Reyha24 - 3 months ago 7x
Python Question

Is this slicing behavior defined?

I am dealing with Python's slicing and I encountered unexpected results.


print([1, 2, 3][0:-4:-1])


print([1, 2, 3][0:-3:-1])
print([1, 2, 3][0:-2:-1])
print([1, 2, 3][0:-1:-1])

Each of these returns
(as expected).

How does this happen?

Thanks, Reyha24.


In a slice, the first item (start) is inclusive. The second argument (stop) is exclusive. When a stop of -3 is given, that means to go from 1, to 1. Since the stop is exclusive, that excludes the only item, and the result is empty. When -2 is given, it translates to index 1. As soon as index 0 is given, you have already passed index 1 because the step is negative. Therefore, the result is empty. You get something similar with -1. Taking -4 from the end, however, becomes -1 because there are only three items in the list. Going from 0 to -1 with a negative step is possible: index 0 is included, index -1 is not because it shows up later in the list.