 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Ordered tuples extraction
When it is required to extract ordered tuples, a list comprehension, the ‘sorted’ method, the ‘tuple’ method and the ‘==’ operator is used.
Example
Below is a demonstration of the same −
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)  Output
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)]
Explanation
- A list of integers is defined and is displayed on the console. 
- A list comprehension is used to iterate over the list, and every element is sorted and converted to a tuple and compared to the element. 
- If they are equal, it is converted to a list, and is assigned to a variable. 
- This is the output that is displayed on the console. 
Advertisements
 