python program to slice lists

Python Program to slice lists

In this article, we will see a Python program to slice lists. But, before proceeding further, we recommend you understand the list from List in Python.

What is Slicing in Python

Extracting a specific part of a list is called slicing. Slicing is done with the help of index value.

Python Slicing Syntax :

listVariable[start index:End index:Step value]

Purpose of Start Index: The start index is the number from which you want to start your sublist. By default value of start index is 0.

Purpose of End Index: The end index is the number from which you want to end your sublist but it is not included in your sublist. By default value of end index is the length of a list.

Purpose of Step Value: Step value refers to what increment you want. By default step value is 1.

Let’s see a python program to slice lists :

Below are examples of Python slicing.

Example 1:

L = [12,'a',6,'b',8]
print(L[1:4:1])


Output :

['a', 6, 'b']

Example 2:

L = [12,'a',6,'b',8]
print(L[1:4])


Output :

['a', 6, 'b']

In the above example, we omit the step value. So it takes default step value 1.

Example 3:

L = [12,'a',6,'b',8]
print(L[:4])


Output :

[12, 'a', 6, 'b']

In the above example, we omit the start value, so it takes a default start index i.e 0.

Example 4:

L = [12,'a',6,'b',8]
print(L[1:])


Output :

['a', 6, 'b', 8]

In the above example, we omit the end index, so it takes the default value length of a list i.e. 5

Example 5:

L = [12,'a',6,'b',8]
print(L[:])


Output :

[12, 'a', 6, 'b', 8]

In the above example, we omit the start and end index values so it takes default values (0 and 5). That’s why the complete list will be printed.

Example 6:

L = [12,'a',6,'b',8]
print(L[::]) # Here we omit all the values


Output :

[12, 'a', 6, 'b', 8]

Example 7:

L = [12,'a',6,'b',8,9,10,11]
print(L[1:6:2])


Output :

['a', 'b', 9]

In the above example, we take a step value as 2 so it prints a sublist with take two steps.

Instead of taking a positive index value, we can also take a negative index value. Let’s see the below example.

Example 8:

L = [12,'a',6,'b',8,9,10,11]
print(L[-4:-1])


Output :

[8, 9, 10]

Example 9:

L = [12,'a',6,'b',8,9,10,11]
print(L[-4:8])


Output :

[8, 9, 10, 11]

In the above example, we take the step value as negative then it will reverse our list.

Example 10:

L = [12,'a',6,'b',8,9,10,11]
print(L[::-1])


Output :

[11, 10, 9, 8, 'b', 6, 'a', 12]

Example 11:

L = [12,'a',6,'b',8,9,10,11]
print(L[::-2])


Output :

[11, 9, 'b', 'a']

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!