![]() |
VOOZH | about |
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).
[2, 3, 4]
list_name[start : end : step]
Parameters:
Let’s see how to use list slicing in Python with the examples below.
To retrieve all items from a list, we can use slicing without specifying any parameters.
[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.
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.
[3, 4, 5, 6, 7, 8, 9] [1, 2, 3]
To extract elements between two specific positions, specify both the start and end indices
[2, 3, 4]
To extract elements at specific intervals, use the step parameter.
[1, 3, 5, 7, 9] [2, 5, 8]
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 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.
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.
[8, 9] [1, 2, 3, 4, 5, 6] [6, 7, 8] [2, 4, 6, 8]
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.
[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.