简体   繁体   中英

How to read slicing with negative step

I have already seen some questions about slicing, but haven't seen a helpful answer concerning some of them, which I can't manage to understand very well. Let's say we have this list a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] And I slice it in the following way:

a[:8:-1] #Ouput: [9]

Why? We give it an end of 8, and a step of -1. How come it behaves in this way?

If you omit the first part of the slice expression, it defaults to None . When it comes time for list.__getitem__ to interpret what slice(None, 8, -1) means, it uses the sign of the step size to determine if you are counting up from 0 or down from the end of the list. In this case, you are counting down, so :8:-1 is equivalent to slice(-1, 8, -1) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM