Home > Backend Development > Python Tutorial > How to Sort Lists or Tuples of Lists/Tuples by a Specific Index Element?

How to Sort Lists or Tuples of Lists/Tuples by a Specific Index Element?

Mary-Kate Olsen
Release: 2024-12-21 15:35:17
Original
712 people have browsed it

How to Sort Lists or Tuples of Lists/Tuples by a Specific Index Element?

Sorting Lists/Tuples of Lists/Tuples by Element at a Specific Index

Sorting lists or tuples of lists or tuples based on an element at a specific index can be achieved using lambda functions. The common approach is to use the built-in sorted() function or the list/tuple's sort() method with a custom key function.

For instance, considering the given data:

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 by the second element of each subset, you can use the following snippet:

sorted_by_second = sorted(data, key=lambda tup: tup[1])
Copy after login

Alternatively, you can sort in place using the sort() method:

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

By default, sorting is done in ascending order. To sort in descending order, specify reverse=True:

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

Note that using tuples instead of lists preserves immutability, which may be desired in some scenarios.

The above is the detailed content of How to Sort Lists or Tuples of Lists/Tuples by a Specific Index Element?. 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