- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
def tuple_sort(my_tup): my_tup.sort(key = lambda x: x) 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))
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)]
- 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.
- 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
- Convert list of tuples to list of list in Python
- Summation of tuples in list in Python
- Perform custom sorting in MySQL
- Convert list of strings to list of tuples in Python
- Convert list of tuples to list of strings in Python
- Finding frequency in list of tuples in Python
- Update a list of tuples using another list in Python
- Convert dictionary to list of tuples in Python
- Convert list of tuples into digits in Python
- List of tuples to dictionary conversion in Python
- Python program to find Tuples with positive elements in List of tuples