Home > Backend Development > Python Tutorial > How to Sort Lists/Tuples by Inner Element Index in Python?

How to Sort Lists/Tuples by Inner Element Index in Python?

Susan Sarandon
Release: 2024-12-25 22:54:19
Original
373 people have browsed it

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)]
Copy after login

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]
Copy after login

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])
Copy after login

To sort the list in-place, use sort():

data.sort(key=lambda tup: tup[1])
Copy after login

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)
Copy after login

or:

data.sort(key=lambda tup: tup[1], reverse=True)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template