Friday, July 27, 2012

Slicing a list: If Step is -1, then.. how?



>>> lst = [1,2,3,4]
>>> print lst[::-1]
[4, 3, 2, 1]
>>> print lst[1:3:-1]
[]
>>> print lst[:2:-1]
[4]
>>> print lst[:3:-1]
[]
>>> print lst[:1:-1]
[4, 3]
>>> print lst[:2:-1]
[4]
>>> print lst[:0:-1]
[4, 3, 2]
>>> print lst[:2:-1]
[4]
>>>
>>> print lst[3:1:-1]
[4, 3]
>>> print lst[3:0:-1]
[4, 3, 2]
>>> print lst[2:0:-1]
[3, 2]
>>>



Step = -1 : start from the rightmost element of the slice
mid element=0 : the first element to exclude from the slice
first element=2: the first element to start the slice from (but step is -1, so this must be rightmore.)

mid element=0: the first element to exclude
first element='' : start from the first RIGHTMOST element (since step = -1.)

In conclusion, if step is -ve, start from the right side, quantity is the number of steps to jump after the first (rightmost) element.


>>> print lst[::-2]
[4, 2]
>>> print lst[::-3]
[4, 1]
>>>






No comments:

Post a Comment