HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How to sort a list/tuple of lists/tuples by the element at a given index

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
indexhowsorttupletuplesliststheelementlistgiven

Problem

I have some data either in a list of lists or a list of tuples, like this:

data = [[1,2,3], [4,5,6], [7,8,9]]
data = [(1,2,3), (4,5,6), (7,8,9)]


And I want to sort by the 2nd element in the subset. Meaning, sorting by 2,5,8 where 2 is from (1,2,3), 5 is from (4,5,6). What is the common way to do this? Should I store tuples or lists in my list?

Solution

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


or:

data.sort(key=lambda tup: tup[1])  # sorts in place


The default sort mode is ascending. To sort in descending order use the option reverse=True:

sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True)


or:

data.sort(key=lambda tup: tup[1], reverse=True)  # sorts in place

Code Snippets

sorted_by_second = sorted(data, key=lambda tup: tup[1])
data.sort(key=lambda tup: tup[1])  # sorts in place
sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True)
data.sort(key=lambda tup: tup[1], reverse=True)  # sorts in place

Context

Stack Overflow Q#3121979, score: 1544

Revisions (0)

No revisions yet.