Good explanation of slicing notation Python

Guilin Zhu
1 min readFeb 18, 2020

--

The slicing notation is commonly used for matrix or array operation, and in order to understand how the slicing notation for python works, here is the good note I took from Stackflow:

>>> seq[:]                # [seq[0], seq[1],   ..., seq[-1] ]
>>> seq[low:] # [seq[low], seq[low+1], ..., seq[-1]]
>>> seq[:high] # [seq[0], seq[1], ..., seq[high-1]]
>>> seq[low:high] # [seq[low], seq[low+1],..., seq[high-1]]
>>> seq[::stride] # [seq[0], seq[stride],..., seq[-1]]
>>> seq[low::stride] # [seq[low], seq[low+stride],..., seq[-1]]
>>> seq[:high:stride] # [seq[0], seq[stride] ,...,seq[high-1]]
>>> seq[low:high:stride] # [seq[low],seq[low+stride],.,seq[high-1]]

Of course, if (high-low)%stride != 0, then the end point will be a little lower than high-1.

If stride is negative, the ordering is changed a bit since we're counting down:

>>> seq[::-stride]        # [seq[-1],   seq[-1-stride],   ..., seq[0]    ]
>>> seq[high::-stride] # [seq[high], seq[high-stride], ..., seq[0] ]
>>> seq[:low:-stride] # [seq[-1], seq[-1-stride], ..., seq[low+1]]
>>> seq[high:low:-stride] # [seq[high], seq[high-stride], ..., seq[low+1]]

The slicing notation is related to the ‘slice()’ function

a[start:end:step] is equivalent to a[slice(start, end, step)]

For example:

a[-1]    # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items

Source: https://stackoverflow.com/questions/509211/understanding-slice-notation

--

--

Guilin Zhu
Guilin Zhu

Written by Guilin Zhu

Computer Vision, AI & Robotics at Georgia Institute of Technology

No responses yet