Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of tuples by 2nd item (integer value) [duplicate]

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?

like image 527
Amyth Avatar asked May 22 '12 02:05

Amyth


People also ask

How do you sort by 2nd value in tuple?

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().

How do I sort a second item in a list Python?

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.

How do you sort a list of tuples based on first value?

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.

Can list and tuple have duplicate values?

Allows duplicate members. Use square brackets [] for lists. Tuple is a collection which is ordered and unchangeable. Allows duplicate members.


1 Answers

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].

like image 199
cheeken Avatar answered Oct 01 '22 08:10

cheeken