[Tutor] Negative step in Python slicing

Alan Gauld learn2program at gmail.com
Sat Nov 13 06:10:36 EST 2021


Always use Reply-All or Rely-List when responding to tutor emails.

On 13/11/2021 01:13, Sahilpreet Singh wrote:
> Thanks Alan 
> But can you explain some cases where step is like -2 or -3.

It is exactly like -1 except it steps by the number shown.
In the same way as 2 or 3 step forward.

The easiest way is to try it in the interpreter:

>>> s = [1,2,3,4,5,6,7,8,9]
>>> s[::-2]  #every second item in reverse...
[9, 7, 5, 3, 1]
>>> s[::-3]  #every third item in reverse...
[9, 6, 3]
>>>

As I said...


>     Slicing consists of 3 values:
>
>     mylist[start:end:step]
>
>     where
>     start defines the first position,
>     end the last position and
>     step the number of intermediate entries
>
>     ...
>

>     Each of these parameters has a default value:
>     start = 0, end = len(mylist), step = 1
>
>
...


>     The step value states how many elements in the original
>     sequence must be stepped over for each element in the
>     slice. Thus 2 returns every second element, 3 every third etc.
>
>     We can also use negative value to indicate direction
>     of traversal. Thus -1 indicates an index of the last element,
>     or a reverse direction of step
>
>     Thus mylist[::-1]
>
>     returns a reversed list
>
>     >>> s[:]
>     [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>
>     Start at 3 and get every second item
>     >>> s[3::2]
>     [3, 5, 7, 9]
>
>     Reverse the list
>     >>> s[::-1]
>     [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>
>     -- 
>
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list