I have a list of tuples that looks something like this:
[('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
I want to sort this list in ascending order by the integer value inside the tuples. Is it possible?
In python, if you want to sort a list of tuples by the second element then we have the function called sort() and by using lambda function as a key function. A custom comparator is a key function in sort().
Use the key argument of the sorted() function to sort a list of tuples by the second element, e.g. sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) . The function will return a new list, sorted by the second tuple element.
Using sorted() function or in place sort are the ways to Sort a list of tuples by the first element in Python. Both methods need to use the key keyword. Note: key should be a function that identifies how to retrieve the comparable element from your data structure.
Allows duplicate members. Use square brackets [] for lists. Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Try using the key
keyword with sorted()
.
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=lambda x: x[1])
key
should be a function that identifies how to retrieve the comparable element from your data structure. In your case, it is the second element of the tuple, so we access [1]
.
For optimization, see jamylak's response using itemgetter(1)
, which is essentially a faster version of lambda x: x[1]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With