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.
[start:stop: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. examples
>>> str = "python" >>> str[0:5:2] 'pto'

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

>>> str = "python" >>> str[0] 'p'

Last Item

>>> str = "python" >>> str[5] 'n'
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.
>>> str = "python" >>> str[1:4] 'yth'

Omit the first index

>>> str = "python" >>> str[:4] 'pyth'

Omit the second index

>>> str = "python" >>> str[4:] 'on'
If you omit both index you will get the copy of the whole array.
>>> str = "python" >>> str[:] 'python'

All items in the array(reversed)

>>> str = "python" >>> str[::-1] 'nohtyp'

Get the last item

>>> str = "python" >>> str[-1] 'n'

Get the last two items

>>> str = "python" >>> str[-2:] 'on'

Everything except the last two items

>>> str = "python" >>> str[:-2] 'pyth'

First two items (reversed)

>>> str = "python" >>> str[1::-1] 'yp'

Last two items (reversed)

>>> str = "python" >>> str[:-3:-1] 'no'

Everything except the last two items (reversed)

>>> str = "python" >>> str[-3::-1] 'htyp'

Every second item in the reversed sequence

>>> str = "python" >>> str[::-2] 'nhy'

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. example
>>> str = "python" >>> str[0:10] 'python'