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
Mary-Kate OlsenOriginal
2024-12-21 15:35:17711browse

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)]

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])

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

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

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)

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!

Statement:
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