
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Order Tuples Using External List in Python
When it is required to order the tuples using an external list, the list comprehension, and ‘dict’ method can be used.
Below is the demonstration of the same −
Example
my_list = [('Mark', 34), ('Will', 91), ('Rob', 23)] print("The list of tuple is : ") print(my_list) ordered_list = ['Will', 'Mark', 'Rob'] print("The ordered list is :") print(ordered_list) temp = dict(my_list) my_result = [(key, temp[key]) for key in ordered_list] print("The ordered tuple list is : ") print(my_result)
Output
The list of tuple is : [('Mark', 34), ('Will', 91), ('Rob', 23)] The ordered list is : ['Will', 'Mark', 'Rob'] The ordered tuple list is : [('Will', 91), ('Mark', 34), ('Rob', 23)]
Explanation
The list of tuple is defined, and is displayed on the console.
Another list is defined, and is displayed on the console.
The list of tuple is converted into a dictionary.
It is iterated over and the elements are stored in another list.
This results in an ordered tuple which is displayed as output on the console.
Advertisements