How to sort with lambda in Python
To sort a list by custom rules in Python, you can use a lambda function as the key
argument in the sorted()
function. For instance, if you need to sort a list of tuples by the second element:
This will give you [(2, 'apple'), (3, 'orange'), (1, 'pear')]
, sorted alphabetically by fruit names. If you want to reverse the order, just use reverse=True
:
Now you'll get [(1, 'pear'), (3, 'orange'), (2, 'apple')]
β same fruits, but the order is reversed.
Behind-the-scenes: Sorting objects by attributes
Lambdas are not just for tuples or basic data types. They can also come in handy when sorting more complex objects, like, say, a list of your custom class instances.
Sorting multiple attributes
There might be situations where you want to sort by several attributes. A good example is sorting a list of books by both year and title:
To troubleshoot potential errors when using lambda with the sorted function, always make sure that the lambda function has been given with key=
. Drop and give me 20 if you've forgotten to do that!
String sorting nuances
If you're sorting strings, it's possible to prioritize length over lexicographic order:
Don't create a new list, sort on the fly!
If you fancy in-place sorting, use the sort()
method, which conveniently takes key=
and reverse=
parameters too:
Mastering the nuance of functools.cmp_to_key
In Python 3.x, a custom comparison function can be converted into a key function for sorting, using cmp_to_key
. Here's how you do it:
What to do when you see an error
If you encounter an error when sorting, don't panic! Error messages are your friends, providing hints on what went wrong. The messages will vary between Python 2.x and 3.x, but remember to always check your key=
function first.
Troubleshooting
- Sort based on date attributes with
key=lambda x: x.date_attribute
. - If you're working with nested structures like a list of dicts with lists, try
key=lambda x: x['list_key'][index]
. - Take advantage of the fact that in sorting, Python treats
True
as 1 andFalse
as 0.
Was this article helpful?