Sometimes, we want to sort a list of tuples by 2nd item with Python.
In this article, we’ll look at how to sort a list of tuples by 2nd item with Python.
How to sort a list of tuples by 2nd item with Python?
To sort a list of tuples by 2nd item with Python, we can use the sorted
function.
For instance, we write
l = sorted([("abc", 121), ("abc", 231), ("abc", 148), ("abc", 221)], key=lambda x: x[1])
to call sorted
with a list and the key
argument set to a function that returns the item to sort by in the tuple.
And then we assign the returned sorted list to l
.
Conclusion
To sort a list of tuples by 2nd item with Python, we can use the sorted
function.