简体   繁体   中英

Python3 slicing negative stop and negative step

Please see below statements, from 1 to 4, this all makes sense and is inline to what I know about python slicing. But I can't explain the outcome of Statement no 5. Can anyone help explain the outcome of statement 5...

x = [1,2,3,4,5,6,7,8,9,10]

#1
print(x[::-2]) 
# prints [10, 8, 6, 4, 2]

#2
print(x[:-2])
# prints [1, 2, 3, 4, 5, 6, 7, 8]

#3
print(x[:-2][::-2])
# prints [8, 6, 4, 2]

#4
print(x[::-2][:-2])
# prints [10, 8, 6]

#5 (please explain this one)
print(x[:-2:-2])
#prints [10]

As you can see from example #1, when you have a negative step value but leave off the start, it works backward starting at the last. So the first value is the last one in the list , which is 10 at index -1 .

The end is given as -2 , which means the second from the last. But since your step is -2 , the next in the sequence would be index -3 which is past -2 . So the sequence ends immediately.

#5 (please explain this one)
print(x[:-2:-2])
#prints [10]

It just starts from 0 index and stop at -2(means it will go upto third term from last) then it starts incrementing by -2. Slice syntax:

x[start:stop:step]

So definitely 10 will be printed

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