Sometimes, while working with list of tuples, we can have a problem in which we need to perform it’s sorting. Naive sorting is easier, but sometimes, we have to perform custom sorting, i.e by decreasing order of first element and increasing order of 2nd element. And these can also be in cases of different types of tuples. Let’s discuss certain cases and solutions to perform this kind of custom sorting.
Method #1 : Using
sorted() + lambda
This task can be performed using the combination of above functions. In this, we just perform the normal sort, but in addition we feed a lambda function which handles the case of custom sorting discussed above.
The original list is : [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)] The tuple after custom sorting is : [(10, 1), (10, 4), (7, 5), (7, 8), (5, 6)]
Method #2 : Using
sorted() + lambda() + sum() ( With sum of tuple condition)
In this method, similar solution sustains. But the case here is that we have tuple as the 2nd element of tuple and its sum has to considered for sort order. Other functions than summation can be extended in similar solution.
The original list is : [(7, (8, 4)), (5, (6, 1)), (7, (5, 3)), (10, (5, 4)), (10, (1, 3))] The tuple after custom sorting is : [(10, (1, 3)), (10, (5, 4)), (7, (5, 3)), (7, (8, 4)), (5, (6, 1))]
- Python - Custom length tuples from String
- Python | Remove tuples from list of tuples if greater than n
- Python | Convert string tuples to list tuples
- Python | Remove duplicate tuples from list of tuples
- Python | Count tuples occurrence in list of tuples
- Python | Find the tuples containing the given element from a list of tuples
- Python | Remove tuples having duplicate first value from given list of tuples
- Python | Combining tuples in list of tuples
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Convert list of strings to list of tuples
- Python | Convert list of tuples to list of strings
- Python - Convert Tuple value list to List of tuples
- Python | Convert list of tuples to list of list
- Python | Update a list of tuples using another list
- Python - Add list elements to tuples list
- Python | Convert list of tuples into list
- Python | Min and Max value in list of tuples
- Python | Sorting list of lists with similar list elements
- Python - N Random Tuples list
- Python | List of tuples Minimum
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.