Slicing List of Tuples in Python
Last Updated :
13 Feb, 2024
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.
Basic Slicing
Here, list_of_tuples[1:3]
retrieves tuples at index 1 and 2, creating a new list [(2, 'banana'), (3, 'cherry')]
.
Python3
list_of_tuples = [( 1 , 'apple' ), ( 2 , 'banana' ), ( 3 , 'cherry' ), ( 4 , 'date' )]
sliced_result = list_of_tuples[ 1 : 3 ]
print (sliced_result)
|
Output
[(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
list_of_tuples = [( 1 , 'apple' ), ( 2 , 'banana' ), ( 3 , 'cherry' ), ( 4 , 'date' )]
sliced_result = list_of_tuples[:: 2 ]
print (sliced_result)
|
Output
[(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
list_of_tuples = [( 1 , 'apple' ), ( 2 , 'banana' ), ( 3 , 'cherry' ), ( 4 , 'date' )]
sliced_result = list_of_tuples[ - 3 : - 1 ]
print (sliced_result)
|
Output
[(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
list_of_tuples = [( 1 , 'apple' ), ( 2 , 'banana' ), ( 3 , 'cherry' ), ( 4 , 'date' )]
sliced_result = [tup for tup in list_of_tuples if tup[ 0 ] % 2 = = 0 ]
print (sliced_result)
|
Output
[(2, 'banana'), (4, 'date')]
Share your thoughts in the comments
Please Login to comment...