Reyha24 - 8 months ago 45

Python Question

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

**Example:**

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

Returns

`[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

`[]`

How does this happen?

Thanks, Reyha24.

Answer

In a slice, the first item (start) is inclusive. The second argument (stop) is *ex*clusive. 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.