-
Notifications
You must be signed in to change notification settings - Fork 0
Python Tips
Leon edited this page Apr 17, 2020
·
1 revision
-
(Reverse)Slice
As we know, slice is very useful in python. Normally we use
a[x:y:d]to make a slice from a list. This is quiet easy to understand, but when it comes to assigning a negative value to “d”, things become confusing.For example: Let’s create a list:
a = [1,2,3,4,5,6]With input:
a[::-1]Obviously we got:[6,5,4,3,2,1]With:
a[:3:-1]Output is:[6,5]With:
a[3::-1]Output is:[4,3,2,1]With:
a[4:2:-1]Output is: >[5,4]With:
a[2:4:-1]Output is: >[]Summary:
When the step parameter becomes a negative value, the indexes of elements won’t change, but the start and the end position are switched!!!
Besides, if there is a direction conflict, it will always return an empty list
[]