Python Slice Operator

Python slicing is a computationally fast way to methodically access parts of your data. The colons (:) in subscript notation make slice notation - which has the optional arguments, start, stop and step . With this operator, one can specify where to start the slicing, where to end, and specify the step.

  1. start: the beginning index of the slice.
  2. stop: the ending index of the slice.
  3. step: the amount by which the index increase.

How slice indexing works?

Python Slice Operator
  1. In forward direction, starts at 0 and ends at len-1.
  2. In backward direction, starts at -1 and ends at -len.

You can make any of these positive or negative numbers. The meaning of the positive numbers is straightforward, but for negative numbers, just like indexes in Python , you count backwards from the end for the start and stop, and for the step, you simply decrement your index.


In the above code start=0 , stop=5 and step=2. So, start from index 0 and stop at index 5 (6th character) and increment is 2. The result is "pto".

First Item

Last Item

The Python Slice Pperator [x:y] returns the part of the string from the x'th character to the y'th character, including the first but excluding the last. If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string.

Omit the first index

Omit the second index

If you omit both index you will get the copy of the whole array.

All items in the array(reversed)

Get the last item

Get the last two items

Everything except the last two items

First two items (reversed)

Last two items (reversed)

Everything except the last two items (reversed)

Every second item in the reversed sequence

Index out of range error?

Be surprised: slice does not raise an IndexError when the index is out of range!

The index out of range means that the index you are trying to access does not exist. If the index is out of range, Python will try its best to set the index to 0 or len(s) according to the situation.

 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About