Sort a list of tuples by 2nd item (integer value)
Sort a list of tuples by the second item with Python's sorted()
function. Use a lambda as the key:
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()
:
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:
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:
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:
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:
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:
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:
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()
:
Now, who would've thought sorting by the absolute value of the second item could be so much fun!
Was this article helpful?