[Tutor] Negative step in Python slicing

Alan Gauld alan.gauld at yahoo.co.uk
Fri Nov 12 09:50:01 EST 2021


On 12/11/2021 12:26, Sahilpreet Singh wrote:
> I am unable to understand how the following works in Python:
> mylist[::k]
> Where mylist is any iterable and k is any constant value.

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

In addition it helps to think of the slice operating with
a "knife blade" inserted to the left of the start/end values

Thus mylist[0:10:1]

extracts every element(step=1) from the start at 0 to
the end at 10. ie elements 0 through 9 given the "knife"
rule above.

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

So we can define

mylist[::] and get a copy of mylist.
We can also miss out the second colon for the same result.

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

And mylist[:5:-1]

returns the reverse of the list as far as the 5th element
(using the knife rule the index is on the right side for a
reverse traversal)

Thus turning to your example

mylist[::k]

is the same as:

mylist[0:len(mylist):k]

Lets look at some real examples:

>>> s = list(range(10))

The original list
>>> s[::]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 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]

Start at position 3 but go backwards
>>> s[3::-1]
[3, 2, 1, 0]

End at position 6
>>> s[:6:-1]
[9, 8, 7]

I hope that helps, carry on trying things out
yourself for other cases. slicing is very powerful
and flexible but not always intuitive.

--
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