- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort list of tuples by specific ordering in Python
When it is required to sort the list of tuples in a specific order, the 'sorted' method can be used.
The 'sorted' method is used to sort the elements of a list.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list.
Below is a demonstration for the same −
Example
def tuple_sort(my_tup): return(sorted(my_tup, key = lambda x: x[1])) my_tuple = [('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)] print("The list of tuple is : ") print(my_tuple) print("The tuple after placing in a specific order is : ") print(tuple_sort(my_tuple))
Output
The list of tuple is : [('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)] The tuple after placing in a specific order is : [('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]
Explanation
- A method named 'tuple_sort' is defined that takes a list of tuple as parameter.
- It uses the 'sorted' method to sort the list of tuple in the order based on the first element in every tuple inside the list of tuple.
- A list of tuple is defined, and is displayed on the console.
- The function is called by passing this list of tuple as parameter.
- This operation's data is stored in a variable.
- This variable is the output that is displayed on the console.
Advertisements