Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

If you want to sort a list of tuples by 2nd item in ascending order you can do by using the sorted function. Below is the code for the same which shows how to do it.

sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=lambda x: x[1])


In the above code, the key is a function that identifies how to retrieve the comparable element from your data structure. So you are using the second element of the tuple.

Another good way of doing this by using the itemgetter function.

from operator import itemgetter

data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)] sorted(data,key=itemgetter(1))


Related questions

0 votes
1 answer
asked Aug 1, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94k users

Browse Categories