Slicing List of Tuples in Python
Slicing, a powerful feature in Python, allows us to extract specific portions of data from sequences like lists. When it comes to lists of tuples, slicing becomes a handy tool for extracting and manipulating data. In this article, we’ll explore five simple and versatile methods to slice lists of tuples in Python, accompanied by code examples.
Slicing List Of Tuples in Python
Below, are examples of How to Slicing a List Of Tuples In Python.
- Extended Slicing with Stride
- Slicing with Negative Indices
- Conditional Slicing
Basic Slicing
Here, list_of_tuples[1:3]
retrieves tuples at index 1 and 2, creating a new list [(2, 'banana'), (3, 'cherry')]
.
Python3
# Sample List of Tuples list_of_tuples = [( 1 , 'apple' ), ( 2 , 'banana' ), ( 3 , 'cherry' ), ( 4 , 'date' )] # Basic Slicing sliced_result = list_of_tuples[ 1 : 3 ] print (sliced_result) |
[(2, 'banana'), (3, 'cherry')]
List Of Tuples Extended Slicing with Stride
In this example, list_of_tuples[::2]
extracts tuples with a stride of 2, resulting in [(1, 'apple'), (3, 'cherry')]
.
Python3
# Sample List of Tuples list_of_tuples = [( 1 , 'apple' ), ( 2 , 'banana' ), ( 3 , 'cherry' ), ( 4 , 'date' )] # Extended Slicing with Stride sliced_result = list_of_tuples[:: 2 ] print (sliced_result) |
[(1, 'apple'), (3, 'cherry')]
List Of Tuples Slicing with Negative Indices
Negative indices allow us to count elements from the end. list_of_tuples[-3:-1]
retrieves tuples at index -3 and -2, yielding [(2, 'banana'), (3, 'cherry')]
.
Python3
# Sample List of Tuples list_of_tuples = [( 1 , 'apple' ), ( 2 , 'banana' ), ( 3 , 'cherry' ), ( 4 , 'date' )] # Slicing with Negative Indices sliced_result = list_of_tuples[ - 3 : - 1 ] print (sliced_result) |
[(2, 'banana'), (3, 'cherry')]
Slicing List Of Tuples Using Conditional Slicing
Here, we use list comprehension to conditionally slice tuples based on the first element. The result is [(2, 'banana'), (4, 'date')]
.
Python3
# Sample List of Tuples list_of_tuples = [( 1 , 'apple' ), ( 2 , 'banana' ), ( 3 , 'cherry' ), ( 4 , 'date' )] # Conditional Slicing with List Comprehension sliced_result = [tup for tup in list_of_tuples if tup[ 0 ] % 2 = = 0 ] print (sliced_result) |
[(2, 'banana'), (4, 'date')]