Explain Codes LogoExplain Codes Logo

How to sort with lambda in Python

python
lambda
functions
best-practices
Alex KataevbyAlex KataevΒ·Feb 21, 2025
⚑TLDR

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:

# Let's sort some fruits 🍎🍊🍐 my_tuples = [(1, 'pear'), (2, 'apple'), (3, 'orange')] # Our trusty lambda will do all the hard work πŸ’ͺ sorted_tuples = sorted(my_tuples, key=lambda x: x[1])

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:

# Sorting fruits, but this time we're contrarians πŸ”„ sorted_tuples_desc = sorted(my_tuples, key=lambda x: x[1], 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:

# List of some really thought-provoking books πŸ“š books = [{'title': 'Brave New World', 'year': 1932}, {'title': '1984', 'year': 1949}, {'title': 'Animal Farm', 'year': 1945}] # Sort them by year first, then by title if the years are the same sorted_books = sorted(books, key=lambda x: (x['year'], x['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:

# Some fruit again, because an apple a day... strings = ['banana', 'pie', 'apple', 'cherry'] # Sort first by length, then alphabetically sorted_strings = sorted(strings, key=lambda x: (len(x), x)) # Now the pie is first πŸ₯§πŸŽπŸŒπŸ’

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:

# Some digits showing up uninvited πŸ™ˆ numbers = [3, 1, 4, 1, 5, 9, 2, 6] # Lambda to the rescue πŸ¦Έβ€β™€οΈ numbers.sort(key=lambda x: -x)

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:

# Time to do some juggling πŸ€Ήβ€β™‚οΈ from functools import cmp_to_key # Here's your function, all ready to compare def compare_items(a, b): return (a > b) - (a < b) # Now sort the list – remember, we're all about that base, no treble. sorted_list = sorted(items, key=cmp_to_key(compare_items))

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 and False as 0.