Slice Notation in Python

In this tutorial, we are going to learn, how to perform slice notation in Python. In slicing, we have forward slicing as well as backward slicing. Forward slicing starts from ‘0’ and backward slicing starts from ‘-1’. We perform slicing to slice the given object. The sequence may be string, tuple, bytes,  list or range. We can perform slice( ) by three parameters specified by range[start:stop: step].

start –Start parameter refers to starting integer where the slicing of the object starts.

stop – Stop parameter refers integer until which the slicing takes place. The slicing stops at one index before the stop parameter.
step –Step parameter refers the integer value which determines the increment between each index for slicing.

How to perform Slice Notation in Python

We will learn slice Notation with an example. We will perform slice Notation using the list.
Example- Let’s create a random list for slicing.

Input–

a=[2,3,4,5,1]
print(a)

Output–

[2, 3, 4, 5, 1]

As we can see that the above list contains 5 elements. We will try to find the elements 3,4,5 by slicing.

Input–

print(a[1:4])

Output–

[3, 4, 5]

Example: Now, We will try to find alternate elements 2,4,1.

Input–

print(a[0:5:2])

Output–

[2, 4, 1]

Example: let’s try out some reverse slicing. We will find elements 1,5,4,3,2 from the above list.

Input–

print(a[-1:0:-1])

Output–

[1, 5, 4, 3]

Example: We will try to find alternate elements in reverse.

Input–

print(a[-1::-2])

Output–

[1, 4, 2]

Also reaD:

Leave a Reply

Your email address will not be published. Required fields are marked *