How to Sort a list of Tuples by Second Value in Python
In this tutorial, we will learn how to sort a list of tuples in ascending order by the second value of each tuple in Python.
To do this, use the Python sort()
function and pass a lambda function that accesses the second element of the tuple as the key value.
tuples = [(3,4), (5,1), (1, 3)]
tuples.sort(key=lambda x:x[1])
print(tuples)
[(5, 1), (1, 3), (3, 4)]
sort()
modifies the original list so it is not necessary to store the result in a new variable.