The Wayback Machine - https://web.archive.org/web/20241119021524/https://www.geeksforgeeks.org/python-list-slicing/
Open In App

Python List Slicing

Last Updated : 28 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python list slicing is fundamental concept that let us easily access specific elements in a list. In this article, we’ll learn the syntax and how to use both positive and negative indexing for slicing with examples.

Example: Get the items from a list starting at position 1 and ending at position 4 (exclusive).

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

# Get elements from index 1 to 4 (excluded)
print(a[1:4])

Output
[2, 3, 4]

Python List Slicing Syntax

list_name[start : end : step]

Parameters:

  • start (optional): Index to begin the slice (inclusive). Defaults to 0 if omitted.
  • end (optional): Index to end the slice (exclusive). Defaults to the length of list if omitted.
  • step (optional): Step size, specifying the interval between elements. Defaults to 1 if omitted

List Slicing Examples

Let’s see how to use list slicing in Python with the examples below.

Get all the items from a list

To retrieve all items from a list, we can use slicing without specifying any parameters.

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

# Get all elements in the list
print(a[::])
print(a[:])

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

Explanation: Using [:] & [::] without specifying any start, end, or step returns all elements of the list.

Get all items before/after a specific position

To get all the items from a specific position to the end of the list, we can specify the start index and leave the end blank.
And to get all the items before a specific index, we can specify the end index while leaving start blank.

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

# Get elements starting from index 2
# to the end of the list
b = a[2:]
print(b)

# Get elements starting from index 0 
# to index 3 (excluding 3th index)
c = a[:3]
print(c)

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

Get all items between two positions

To extract elements between two specific positions, specify both the start and end indices

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

# Get elements from index 1 
# to index 4 (excluding index 4)
b = a[1:4]
print(b)

Output
[2, 3, 4]

Get items at specified intervals

To extract elements at specific intervals, use the step parameter.

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

# Get every second element from the list
# starting from the beginning
b = a[::2]
print(b)

# Get every third element from the list
# starting from index 2 to 8(exclusive)
c = a[1:8:3]
print(c)

Output
[1, 3, 5, 7, 9]
[2, 5, 8]

Out-of-bound slicing

In Python, list slicing allows out-of-bound indexing without raising errors. If we specify indices beyond the list length then it will simply return the available items.

Example: The slice a[7:15] starts at index 7 and attempts to reach index 15, but since the list ends at index 8, so it will return only the available elements (i.e. [8,9]).

Negative Indexing

Negative indexing is useful for accessing elements from the end of the list. The last element has an index of -1, the second last element -2, and so on.

Extract elements using negative indices

This example shows how to use negative numbers to access elements from the list starting from the end. Negative indexing makes it easy to get items without needing to know the exact length of the list.

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

# Get elements starting from index -2
# to end of list
b = a[-2:]
print(b)

# Get elements starting from index 0 
# to index -3 (excluding 3th last index)
c = a[:-3]
print(c)

# Get elements from index -4
# to -1 (excluding index -1)
d = a[-4:-1]
print(d)

# Get every 2nd elements from index -8
# to -1 (excluding index -1)
e = a[-8:-1:2]
print(e)

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

Reverse a list using slicing

In this example, we’ll reverse the entire list using a slicing trick. By using a negative step value, we can move through the list in reverse order.

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

# Get the entire list using negative step
b = a[::-1]
print(b)

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

Explanation: The negative step (-1) indicates that Python should traverse the list in reverse order, starting from the end. The slice a[::-1] starts from the end of the list and moves to the beginning which result in reversing list. It’s a quick and easy way to get the list in reverse without changing the original list.




Previous Article
Next Article

Similar Reads

Python | Custom slicing in List
Sometimes, while working with Python, we can come to a problem in which we need to perform the list slicing. There can be many variants of list slicing. One can have custom slice interval and slicing elements. Let's discuss problem to such problem. Method : Using compress() + cycle() The combination of above functions can be used to perform this pa
2 min read
Program to cyclically rotate an array by one in Python | List Slicing
Given an array, cyclically rotate the array clockwise by one. In this article, we will see how to cyclically rotate an array by one in Python. Example Input: arr = [1, 2, 3, 4, 5]Output: arr = [5, 1, 2, 3, 4]Reference: Program to cyclically rotate an array by one Python Program to Cyclically Rotate an Array by One in PythonBelow are the methods or
2 min read
Python List Comprehension and Slicing
List comprehension is an elegant way to define and create a list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
5 min read
Interesting facts about strings in Python | Set 2 (Slicing)
Creating a String Strings in Python can be created using single quotes or double quotes or even triple quotes. # Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World' print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'
4 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
Python Slicing | Reverse an array in groups of given size
Given an array, reverse every sub-array formed by consecutive k elements. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] k = 3 Output: [3, 2, 1, 6, 5, 4, 9, 8, 7] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 Output: [5, 4, 3, 2, 1, 8, 7, 6] Input: arr = [1, 2, 3, 4, 5, 6] k = 1 Output: [1, 2, 3, 4, 5, 6] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k =
5 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).Right (Or clockwise) rotate the given string by d elements (where d <= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python Slicing | Extract ‘k’ bits from a given position
How to extract ‘k’ bits from a given position ‘p’ in a number? Examples: Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is represented as 1001000 in binary, so, you should get o
4 min read
Slicing with Negative Numbers in Python
Slicing is an essential concept in Python, it allows programmers to access parts of sequences such as strings, lists, and tuples. In this article, we will learn how to perform slicing with negative indexing in Python. Indexing in PythonIn the world of programming, indexing starts at 0, and Python also follows 0-indexing what makes Python different
6 min read
Python slicing multi-dimensional arrays
Python's NumPy package makes slicing multi-dimensional arrays a valuable tool for data manipulation and analysis. It enables efficient subset data extraction and manipulation from arrays, making it a useful skill for any programmer, engineer, or data scientist. Python Slicing Multi-Dimensional ArraysSlicing is a method for taking out an array secti
4 min read
String Slicing in Python
String slicing in Python is a way to get specific parts of a string by using start, end, and step values. It’s especially useful for text manipulation and data parsing. Let’s take a quick example of string slicing: [GFGTABS] Python s = "Hello, Python!" # Slice string from index 0 to index 5 (exclusive) s2 = s[0:5] print(s2) [/GFGTABS]Outp
4 min read
Implementing slicing in __getitem__
The __getitem__ method is used for accessing list items, array elements, dictionary entries etc. slice is a constructor in Python that creates slice object to represent set of indices that the range(start, stop, step) specifies. __getitem__ method can be implement in a class, and the behavior of slicing can be defined inside it. Syntax: __getitem__
2 min read
Data Slicing using PyQtGraph
In this article, we will see how we can perform data slicing using PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and sec
5 min read
Basic Slicing and Advanced Indexing in NumPy
Indexing a NumPy array means accessing the elements of the NumPy array at the given index. There are two types of indexing in NumPy: basic indexing and advanced indexing. Slicing a NumPy array means accessing the subset of the array. It means extracting a range of elements from the data. In this tutorial, we will cover basic slicing and advanced in
5 min read
Slicing Pandas Dataframe
Slicing Pandas DataFrames is a powerful technique, allowing extraction of specific data subsets based on integer positions. In this article, let's understand examples showcasing row and column slicing, cell selection, and boolean conditions. Slicing Pandas Dataframe With the help of Pandas, we can perform slicing in Dataframe. Slicing in pandas dat
4 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python List Comprehension | Segregate 0's and 1's in an array list
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Examples: Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python usi
2 min read
Python | Sort list of list by specified index
We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
8 min read
Python | Remove all values from a list present in other list
Sometimes we need to perform the operation of removing all the items from the lists that are present in another list, i.e we are given some of the invalid numbers in one list which need to be get ridden from the original list. Let's discuss various ways How to remove the elements of a list from another list in Python. Illustration: Input: List one
10 min read
Python | Sort list according to other list order
Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let's discuss certain ways to sort list according to other list order. Method #1 : Using List
5 min read
Python | Ways to Convert a 3D list into a 2D list
List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development. Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or while contributing to open source. Below are some w
3 min read
Python | Merge List with common elements in a List of Lists
Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions. Below are some ways to achieve this. Input: [[11, 27, 13], [11, 27, 55], [22, 0, 43], [22, 0, 96], [13, 27, 11], [13, 27, 55], [43, 0, 22], [43, 0, 96], [55, 27, 11]] Out
3 min read
Python | Subtract two list elements if element in first list is greater
Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.Examples: Input: l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] Output: [10, 20, 30, 10, 30, 50] Input: l1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] l2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output: [6, 5,
5 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Appending Item to Lists of list using List Comprehension | Python
If you are a Python user, you would know that in Python, we can use the append() method to add an item to an existing list. This list may already contain other items or be empty. Further, the item to be added can simply be a number a character, or even an entire tuple or list. However, if you are trying to append an item to lists within a list comp
5 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
List methods are discussed in this article. 1. len() :- This function returns the length of list. List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(len(List)) Output: 10 2. min() :- This function returns the minimum element of list. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] print(min(List)) Output: 1.054 3. max() :- This function returns the maximum eleme
2 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg