Home >Backend Development >Python Tutorial >How to Sort Lists/Tuples of Lists/Tuples Based on a Specific Index?
Sorting Lists/Tuples of Lists/Tuples Based on Element at a Specific Index
Data structures like lists and tuples often contain elements that comprise sublists or subtuples. If you encounter the task of sorting such a structure based on an element within each subset, the following techniques provide effective solutions.
Using Tuples or Lists
Both tuples and lists are valid choices for storing your data. Tuples are immutable, meaning their contents cannot be modified after creation. Lists, on the other hand, are mutable and allow for changes to their elements. For sorting purposes, the choice between them depends on your specific scenario.
Sorting by Second Element
To sort a list/tuple of lists/tuples based on the second element in each subset, you can utilize the built-in sorted() function in Python. This function takes an optional key argument that specifies the criterion for sorting.
Using sorted() with a Lambda Function
An elegant approach is to use a lambda function as the key argument. For instance, to sort by the second element in a list of lists, you can do the following:
sorted_by_second = sorted(data, key=lambda tup: tup[1])
Sorting in Place
If you wish to sort the original list/tuple in place without creating a new sorted list, you can use the sort() method instead. This method also accepts a key argument:
data.sort(key=lambda tup: tup[1]) # sorts in place
Customizing Sort Order
By default, sorting occurs in ascending order. To sort in descending order, specify the reverse option:
sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True)
In-Place Sort with Reverse Order
To sort the original list/tuple in place in descending order, use:
data.sort(key=lambda tup: tup[1], reverse=True) # sorts in place
The above is the detailed content of How to Sort Lists/Tuples of Lists/Tuples Based on a Specific Index?. For more information, please follow other related articles on the PHP Chinese website!