Reyha24
Reyha24

Reputation: 31

Is this slicing behavior defined?

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 [](as expected).

How does this happen?

Thanks, Reyha24.

Upvotes: 2

Views: 101

Answers (2)

zondo
zondo

Reputation: 20346

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.

Upvotes: 2

TheBlackCat
TheBlackCat

Reputation: 10328

I think this is clearer if you reverse the slice and convert to regular indexing. Since python uses half-open intervals, [0:-4:-1] converts to [1, 2, 3][-3:1]. -3 in this case corresponds to index 0, so this converts to [1, 2, 3][0:1], which is just the first element. The second case, [0:-3:-1], converts to [-2:1], which is [1:1], which is empty. The third case converts to [2:1], and so on.

Upvotes: 1

Related Questions