
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
Sort a List of Tuples by Second Item in Python
When it is required to sort a list of tuples based on the second item, the lambda function and ‘sorted’ method can be used.
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.
Anonymous function is a function which is defined without a name.
In general, functions in Python are defined using ‘def’ keyword, but anonymous function is defined with the help of ‘lambda’ keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it.
The ‘sorted’ method is used to sort the elements of a list.
Below is a demonstration for the same −
Example
def tuple_sort(my_tuple): return(sorted(my_tuple, key = lambda x: x[1])) my_tuple = [('bill', 11), ('rick', 45), ('john', 89), ('liv', 25)] print("The list of tuple is : ") print(my_tuple) print("After sorting, the list of tuple becomes : ") print(tuple_sort(my_tuple))
Output
The list of tuple is : [('bill', 11), ('rick', 45), ('john', 89), ('liv', 25)] After sorting, the list of tuple becomes : [('bill', 11), ('liv', 25), ('rick', 45), ('john', 89)]
Explanation
- A function named ‘tuple_sort’ is defined, that takes a list of tuple as parameter.
- It is first iterated over using lambda function, and sorted using the ‘sorted’ function.
- This is returned as output.
- A list of tuple is defined and is displayed on the console.
- The ‘tuple_sort’ method is called by passing this list of tuple as parameter.
- This value is displayed as output on the console.
Advertisements