
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Custom sorting in list of tuples in Python
When it is required to sort the list of tuples in a customized manner, the 'sort' method can be used.
The 'sort' method sorts the elements of the iterable in a specific order, i.e ascending or descending. It sorts the iterable in-place.
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 of the same −
Example
def tuple_sort(my_tup): my_tup.sort(key = lambda x: x[1]) return my_tup my_tuple = [('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)] print("The tuple is ") print(my_tuple) print("The sorted list of tuple is :") print(tuple_sort(my_tuple))
Output
The tuple is [('Will', 100), ('John', 67), ('Harold', 86), ('Jane', 35)] The sorted list of tuple is : [('Jane', 35), ('John', 67), ('Harold', 86), ('Will', 100)]
Explanation
- A function named 'tuple_sort' is defined, that takes a list of tuple as argument.
- This method uses the 'sort' method to sort the elements of the tuple using the lambda function.
- Lambda function takes a single expression, but can take any number of arguments.
- It uses the expression and returns the result of it.
- A list of tuple is defined, and is displayed on the console.
- The method is called by passing this list of tuple.
- This is assigned to a value.
- It is displayed on the console.
- Related Articles
- Combining tuples in list of tuples in Python
- Count tuples occurrence in list of tuples in Python
- Remove duplicate tuples from list of tuples in Python
- Convert list of tuples into list in Python
- Summation of tuples in list in Python
- Convert list of tuples to list of list in Python
- Finding frequency in list of tuples in Python
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- Update a list of tuples using another list in Python
- Remove tuples from list of tuples if greater than n in Python
- Python program to find Tuples with positive elements in List of tuples
- Convert dictionary to list of tuples in Python
- List of tuples to dictionary conversion in Python
- Convert list of tuples into digits in Python

Advertisements