donopj2
donopj2

Reputation: 4113

Sort A List of Tuples By Lowest Value

Supposed I have a list of tuples:

my_list = [(1, 4), (3, 0), (6, 2), (3, 8)]

How do I sort this list by the minimum value in the tuple, regardless of position? My final list will be as follows:

my_sorted_list = [(3, 0), (1, 4), (6, 2), (3, 8)]

Upvotes: 2

Views: 1829

Answers (3)

martineau
martineau

Reputation: 123481

sorted(my_list, key=lambda x: x[0] if x[0] < x[1] else x[1])

Upvotes: 1

Hugh Bothwell
Hugh Bothwell

Reputation: 56674

my_sorted_list = sorted(my_list, key=min)

Upvotes: 2

DSM
DSM

Reputation: 353359

You can take advantage of the key parameter, to either .sort or sorted:

>>> my_list = [(1, 4), (3, 0), (6, 2), (3, 8)]
>>> sorted(my_list, key=min)
[(3, 0), (1, 4), (6, 2), (3, 8)]

Upvotes: 8

Related Questions