Table of contents
1.
Introduction
2.
What is List Slice in Python?
3.
Syntax of List Slicing
4.
Methods of slicing
4.1.
Slicing with positive index
4.2.
Python
4.3.
Slicing with negative index
4.4.
Python
5.
Common slicing patterns
5.1.
Reversing a list
5.2.
Python
5.3.
Modifying a given list
5.4.
Python
6.
Slicing in Python
6.1.
Slicing in Tuples
6.2.
Python
6.3.
Slicing in Strings  
6.4.
Python
6.5.
Python
7.
Examples of List Slicing in Python
7.1.
Basic List Slicing
7.2.
Python
7.3.
Negative Indices Slicing
7.4.
Python
8.
Uses of Python List slice
9.
Frequently asked questions
9.1.
What is [:] in Python?
9.2.
When slicing in Python What does the 2 in [:: 2] specify?
9.3.
Can a list be sliced Python?
9.4.
Can we slice a dictionary in Python?
9.5.
What is the default behavior if we omit the start, stop, or step values in slice notation?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Python List Slicing

Author Tashmit
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Do you know, in Python List is a data structure that can store a collection of items. It is mutable; hence, we can edit a list. In order to modify a list, we use slicing. 

Python List Slicing

In this article, we will study how we can slice a list in Python. We will study its syntax, methods, and some common slicing patterns.

What is List Slice in Python?

When we want to extract a specific part of a list, we can use slicing. It is used to extract a subset of data from the list. Slicing of list creates a new list with the extracted elements. 

Note: Slicing does not change the original list. 

Syntax of List Slicing

In order to slice a list, we have to mention three attributes. The start, stop, and step attributes. The syntax to slice is:

list [ start : stop : step ]


Start: The start component determines the starting element of the slicing. This element is also included in the output.

Stop: The stop component determines the end point of the sliced list. It is not included in the sliced list. 

Step: The step component determines the number of elements to skip while slicing a list.

Let us understand various methods of slicing.

Methods of slicing

Below are the methods of slicing.

Slicing with positive index

Positive slicing starts from the first element of the list.

Code

  • Python

Python

lst = ['C','o','d','i','n','g','N','i','n','j','a']
print("Original List: ", lst)

#Slicing first 5 elements with a step of 2.
print("\nList from starting to 5th element with a step of 2 is:", lst[0:5:2])

#Slicing elements from 3 to 8
print("\nList from 3rd to 9th element is:",lst[3:9])

#Slicing elements from index 5 till the last element
print("\nList from 5th element till last element is:",lst[5:])

#Slicing elements all elements till 9 element
print("\nList from starting to 9th element is:",lst[:9])
You can also try this code with Online Python Compiler
Run Code


Output

Output

Slicing with negative index

Negative slicing starts with the last element of the list. 

Code

  • Python

Python

lst = ['C','o','d','i','n','g','N','i','n','j','a']
print("Original List: ", lst)

#Slicing elements from third-last element to the last element
print("\nList from 3rd last to last element is:",lst[-3:])

# Slice elements from the first to the fifth-last index
print("\nList from starting to 5th last element is:",lst[:-5])

# Slice elements from the second-last index to the sixth-last index
print("\nList from 2nd last to 6th element with a step of -1 is:",lst[-2:-6:-1])
You can also try this code with Online Python Compiler
Run Code


Output

Output

Note, that in both the types of slicing, the last element is not included in the output.

Common slicing patterns

When we want to manipulate the list, we use the slicing method. Some of the most common practices of slicing are:

Reversing a list

With the help of slicing, we can reverse a give list, Let us see a code snippet to understand it better.

Code

  • Python

Python

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Original List:", my_list)

# Reverse the entire list
reversed_list = my_list[::-1]
print(reversed_list)
You can also try this code with Online Python Compiler
Run Code


Output

Output

Explanation

In the above code, we created a my_list. We then created another list called reversed_list and stored all the values with a step of -1. Thus the reversed list is created. The output of above code is as follows: 

Modifying a given list

List is mutable, thus we can add, remove and replace elements from a list. Let us see sample code to see how to use slicing to modify a list.

Code

  • Python

Python

my_list = [1, 2, 3, 4, 5, 6]

# Replacing the elements from index 2 to 4 with new values
my_list[2:5] = [7, 8, 9]
print(my_list)

# Delete elements from index 3 to the end of the list
my_list[3:] = []
print(my_list)

# Insert elements at the end using slice
my_list[2:2] = [3, 4, 5]
print(my_list)
You can also try this code with Online Python Compiler
Run Code


Output

Output

Explanation

In the above example, we first replaced all elements from 2 to 4. Then we deleted all the elements from 3rd to the end. Finally, we added elements at the end of the list. 

Slicing in Python

Slicing is not restricted to lists. In Python, we can apply slicing on tuples and strings as well. It is similar to how we do slicing in lists.

Slicing in Tuples

Let us see a code snippet to understand it better

Code

  • Python

Python

my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[1:4])
You can also try this code with Online Python Compiler
Run Code


Output

Output

Slicing in Strings  

The syntax of slicing in strings is similar to that of lists and tuples. Let's see an example for a better understanding.

Code

  • Python

Python

my_string = "Hello, Ninja!"
print(my_string[7:13])
You can also try this code with Online Python Compiler
Run Code


Output

Output

A string is immutable, which means that we cannot modify it. But with the help of slicing we can do that.

Code

  • Python

Python

# Replace characters
new_string = my_string[:7] + "Python!"
print(new_string)
You can also try this code with Online Python Compiler
Run Code


Output

Output

By this method, we can keep the required string and modify it.

Examples of List Slicing in Python

List slicing in Python allows you to extract a portion of a list. Here are some examples:

Basic List Slicing

  • Python

Python

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Get elements from index 2 to 4 (exclusive)
sliced_list = my_list[2:5]
print(sliced_list)

You can also try this code with Online Python Compiler
Run Code

 

Output:

[3,4,5]

 

Explanation:

The code extracts elements from index 2 up to, but not including, index 5. It will output: [3, 4, 5].
 

Negative Indices Slicing

  • Python

Python

# Get last three elements
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
sliced_list = my_list[-3:]
print(sliced_list)

# Get elements from index 2 to 2 from the end (exclusive)
sliced_list = my_list[2:-2]
print(sliced_list)
You can also try this code with Online Python Compiler
Run Code


Output:

[3, 4, 5, 6, 7]

 

Explanation:

The first line extracts the last three elements from my_list using negative indexing. The second line retrieves elements from index 2 to 2 from the end, excluding the last two elements.

Uses of Python List slice

Below are the uses of Python list slice.

  • Extracting a subsequence: We can extract a specific portion of a list.
     
  • Copying a sequence: We can slice a portion of a list and create a copy list of that. 
     
  • Modifying a subsequence: We can modify a specific portion of a list with the help of slicing. 
     
  • Reversing a sequence: We can reverse a list with the help of slicing.
     
  • Skipping elements: With the help of slicing, we can skip some elements from a list by specifying the step value.

    and  Convert String to List Python

Frequently asked questions

What is [:] in Python?

In Python, the operator [:] makes a copy of the entire list and returns a new list with the same elements.

When slicing in Python What does the 2 in [:: 2] specify?

The '2' in [::2] specifies a slice step size of 2, which chooses every second piece.

Can a list be sliced Python?

The Python syntax list[start:end:step] allows you to slice a list, hence the answer is yes. It enables the extraction of particular list segments.

Can we slice a dictionary in Python?

No, we cannot slice dictionaries in Python. It does not support slicing because it is an unordered collection of key-value pairs. Also, it is not indexed.

What is the default behavior if we omit the start, stop, or step values in slice notation?

If we remove the stop attribute, slicing will continue until the end of the list. If we remove the step value, slicing will use a step of 1(default step value).

Conclusion

Slicing allows us to extract, modify, or create new sequences based on mentioned steps. In this article, we studied about slicing in Python. We also studied about the syntax, methods and common patterns used in slicing. To know more about slicing, you can refer to string slicing in Python.

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy learning, Ninja! 

Live masterclass