Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Ordered tuples extraction
When working with tuples, you might need to extract only those tuples that are already in sorted order. Python provides an elegant solution using list comprehension combined with the sorted() function and tuple comparison.
What are Ordered Tuples?
An ordered tuple is a tuple where elements are arranged in ascending order. For example, (13, 24, 56) is ordered, while (15, 74, 36, 22, 54) is not.
Extracting Ordered Tuples
The key idea is to compare each tuple with its sorted version. If they are equal, the tuple is already in order ?
my_list = [(15, 74, 36, 22, 54), (13, 24, 56), (59, 60, 34), (42, 65, 56), (99, 91)]
print("The list is :")
print(my_list)
my_result = [element for element in my_list if tuple(sorted(element)) == element]
print("The result is :")
print(my_result)
The list is : [(15, 74, 36, 22, 54), (13, 24, 56), (59, 60, 34), (42, 65, 56), (99, 91)] The result is : [(13, 24, 56)]
How It Works
The solution uses these key components:
List comprehension: Iterates through each tuple in the list
sorted() function: Returns a sorted list of elements from the tuple
tuple() conversion: Converts the sorted list back to a tuple for comparison
Equality operator (==): Compares the original tuple with its sorted version
Alternative Approach Using Filter
You can also use the filter() function for the same result ?
my_list = [(15, 74, 36, 22, 54), (13, 24, 56), (59, 60, 34), (42, 65, 56), (99, 91)]
def is_ordered(tup):
return tuple(sorted(tup)) == tup
my_result = list(filter(is_ordered, my_list))
print("The ordered tuples are :")
print(my_result)
The ordered tuples are : [(13, 24, 56)]
Checking for Descending Order
To extract tuples in descending order, use reverse=True in the sorted function ?
my_list = [(15, 74, 36, 22, 54), (13, 24, 56), (100, 60, 34), (42, 65, 56), (99, 91)]
# Extract tuples in descending order
desc_result = [element for element in my_list if tuple(sorted(element, reverse=True)) == element]
print("Tuples in descending order :")
print(desc_result)
Tuples in descending order : [(100, 60, 34)]
Conclusion
Use list comprehension with tuple(sorted(element)) == element to extract ordered tuples efficiently. This approach compares each tuple with its sorted version to identify already-ordered sequences.
