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
Selected Reading
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
