Home >Backend Development >Python Tutorial >How to Sort Lists/Tuples by Inner Element Index in Python?
Sorting Lists/Tuples by Inner Element Index
Given a list of lists or tuples, such as:
data = [[1,2,3], [4,5,6], [7,8,9]] data = [(1,2,3), (4,5,6), (7,8,9)]
To sort the list by the second element in each subset, leverage the key parameter within the sorted() or sort() functions. The key determines the sorting criteria. In this case, you want to access the second element of each tuple/list, which can be achieved using the lambda function:
lambda tup: tup[1]
Sorting by Second Element:
Using sorted(), you can sort the list while preserving the original data structure:
sorted_by_second = sorted(data, key=lambda tup: tup[1])
To sort the list in-place, use sort():
data.sort(key=lambda tup: tup[1])
Descending Order:
To sort in descending order, specify reverse=True as an optional parameter:
sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True)
or:
data.sort(key=lambda tup: tup[1], reverse=True)
The above is the detailed content of How to Sort Lists/Tuples by Inner Element Index in Python?. For more information, please follow other related articles on the PHP Chinese website!