Explain Codes LogoExplain Codes Logo

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

python
functions
performance
best-practices
Anton ShumikhinbyAnton Shumikhin·Dec 31, 2024
TLDR

Sort a list of tuples by the second item with Python's sorted() function. Use a lambda as the key:

sorted_by_second = sorted(tuples_list, key=lambda x: x[1])

The command sorts tuples_list precisely by the integer values at index 1 in each tuple.

Speed up with itemgetter

For fast and furious sorting (not the movie), use operator.itemgetter():

from operator import itemgetter # I heard you like going fast. Buckle up! sorted_by_second = sorted(tuples_list, key=itemgetter(1))

Here, itemgetter(1) is quicker off the mark than a lambda, brum brum! 🏎

Ascending or descending, you choose!

To climb or to dive, add reverse=True for descending order:

sorted_by_second_desc = sorted(tuples_list, key=lambda x: x[1], reverse=True)

Surely life would be dreary if we always had to go in one direction.

Rearranging the furniture in-place

For those who like to mutate stuff (in a good way), use list.sort(). It rearranges the original list:

# Rearranging the furniture, not Tetris-style though. tuples_list.sort(key=lambda x: x[1])

Twin emergencies: Identical first elements

When the first elements twin faster than Pandas on a bamboo diet, sorted() ensures the second item gets the VIP pass:

tuples_list = [(3, 2), (3, 1), (3, 3)] # Tell Python to step aside when it sees identical first elements, the second's got a party to attend! sorted_by_second = sorted(tuples_list, key=itemgetter(1))

So we'll be dancing to the rhythm of [(3, 1), (3, 2), (3, 3)].

Complex sorting made easy with lambda

Someone said, complexity is the mother of invention. Lambdas bring power to custom criteria:

sorted_by_custom = sorted(tuples_list, key=lambda x: (x[1], -x[0]))

Which means, sort by the second item but if we find any party crashers (same second item), flip the table (invert the first item)!

Optimizing large datasets

For large datasets, the key to survival is optimized sorting. itemgetter when combined with sorted(), it's like a caffeine boost:

from operator import itemgetter # Like an espresso shot for your data! large_data_sorted = sorted(large_dataset, key=itemgetter(1))

Algorithm fitness is important, especially when data isn't on a diet.

Code readability: The secret recipe

Readability is any coder's secret sauce. itemgetter with sorting makes your code a Michelin star recipe:

# So clear, you'd think it's spring water. readable_sorted = sorted(tuples_list, key=itemgetter(1))

sort() vs sorted(): The hero or the clone

  • sort(): The hero in action, changes the original list.
  • sorted(): The clone, leaves the original untouched. Perfect for déjà vu or when messing up is not an option.

Advanced sorting: Leverage the key

Who said sorting is boring? Swing it with the key in sorted():

# Don't be shy to throw in some acrobats. sorted_by_complex = sorted(tuples_list, key=lambda x: (abs(x[1]), x[0]))

Now, who would've thought sorting by the absolute value of the second item could be so much fun!