Skip to content

Understanding slice notation Python | Use an example

  • by

It’s pretty simple to understand slice notation in Python. The basic slicing technique is to define the starting point, the stopping point, and the step size.

The slicing operator [] is actually being used in the above code with a slice() object using the : notation (which is only valid within []), i.e.:

slice(start, end, step) 

Understanding slice notation Python

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

There is also the step value, which can be used with any of the above:

a[start:stop:step] # start through not past stop, by step

The important point is that the :stop the value represents the value from is not in the selected slice. So, the difference between stop and start is the number of elements selected (if step is 1, the default).

The other thing to know is that start or stop may be a negative number, which means it counts from the end of the array instead of the beginning. So:

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

Similarly, step can be a negative number:

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed


How do I use the slice notation in Python?

Here is an example code using slice notations.

a = ("a", "b", "c", "d", "e", "f", "g", "h")



slice notation Python

Get n first elements of a list

With Slice notation, you can skip any element of the full syntax. If we skip the start the number then it starts from 0 index:

nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]

Output: [10, 20, 30, 40, 50]

Get n last elements of a list

nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]

Output: [70, 80, 90]

Do comment if you have any doubts and suggestions on this Python slice code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading