In Python you can use a lambda function with sorted() to sort lists based on custom rules. It’s a concise way to define sorting logic inline without writing a separate function.

This is useful when working with dynamic sorting, anonymous logic or handling structured data like dictionaries and tuples.

Common Python Sorting Scenarios Using Lambda

Here are 5 practical ways to sort items in Python using lambda — with examples for numbers, tuples, dictionaries and reverse sorting.

1. Sort a List of Numbers (Default)

Sorts the list elements in ascending order based on their natural order (from smallest to largest) using the default comparison method.

numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 5, 9]

2. Sort with Lambda – Custom Key

Use lambda to create custom sort behavior dynamically — like sorting in reverse, by length or by any transformation of the data.

numbers = [5, 2, 9, 1]# Sort by the negative value to reverse using lambda

sorted_numbers = sorted(numbers, key=lambda x: -x)

print(sorted_numbers) # Output: [9, 5, 2, 1]

Also Read: Python’s Role in Shaping the Future of AI & ML in 2025

3. Sort List of Tuples

Sorts a list of tuples based on a particular index, like sorting alphabetically by the second value in each tuple.

items = [(1, ‘apple’), (3, ‘banana’), (2, ‘cherry’)]# Sort by second item in each tuple

sorted_items = sorted(items, key=lambda x: x[1])

print(sorted_items) # Output: [(1, ‘apple’), (3, ‘banana’), (2, ‘cherry’)]

4. Sort List of Dictionaries by Field

Sorts a list of dictionaries by a chosen field key, useful for organizing user data, records or API responses.

people = [    {“name”: “Alice”, “age”: 30},

    {“name”: “Bob”, “age”: 25},

    {“name”: “Charlie”, “age”: 35}

]

# Sort by age

sorted_people = sorted(people, key=lambda person: person[“age”])

print(sorted_people)

5. Sort in Reverse Order

Use lambda with the reverse=True flag to sort items from highest to lowest or from Z to A based on custom logic.

words = [‘banana’, ‘apple’, ‘cherry’]sorted_words = sorted(words, key=lambda x: x, reverse=True)

print(sorted_words)  # Output: [‘cherry’, ‘banana’, ‘apple’]

Tip

lambda is good for quick inline sorting. Use regular functions (def) when logic gets complex or needs to be reused.

Also,

  • sorted() returns a new sorted list
  • .sort() modifies the list in place and works only on lists