Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Lambda Functions for Inline Operations and Custom Comparators

Recommended resources

Hello! Welcome back to our course on Python for Competitive Programming.

In our last lesson, we explored how list and dictionary comprehensions can make your code for creating and transforming collections incredibly concise and efficient. This is a key skill for writing fast, readable solutions under pressure.

Today, we'll continue this theme by diving into lambda functions. You'll learn how to use these small, inline functions to add another layer of power and brevity to your code. Our main focus will be on applying them as custom comparators for sorting, a technique you will use constantly in competitive programming to organize data exactly how you need it.

1. What is a Lambda Function?

A lambda function is a small, anonymous function that you can define in a single line. Think of it as a shorthand for a simple def function.

The syntax is straightforward: lambda arguments: expression

  • lambda: The keyword that declares a lambda function.
  • arguments: The input parameters, just like in a regular function.
  • expression: A single expression that is evaluated and returned.

For example, a function that adds two numbers:
Regular function:

def add(x, y):
    return x + y

Lambda function:

add_lambda = lambda x, y: x + y

# Both can be called the same way
print(add(5, 3))         # Output: 8
print(add_lambda(5, 3))  # Output: 8

The main benefit isn't assigning them to variables, but using them directly where a function is expected.

This image provides a great visual breakdown of the syntax:

Python Lambda Function Syntax Breakdown
This diagram clearly labels the components of a lambda function: the `lambda` keyword, its arguments, and the return expression.

To see this in action, the following video provides a clear introduction to the concept and syntax.

Python Lambda Functions Explained

This clip from the video "Python Lambda Functions Explained" by Tech With Tim introduces the basic syntax and idea behind lambda functions.

Watch from the beginning until 01:23. Pay attention to how a lambda function is defined and how it can accept single or multiple parameters.


2. The Power of key: Custom Sorting with Lambda

The most common and powerful use of lambda functions, especially in competitive programming, is with Python's sorting capabilities. Both the sorted() function (which returns a new sorted list) and the .sort() method (which sorts a list in-place) accept a key argument.

The key argument expects a function that takes a single element from your list and returns a "key" that the sorting algorithm will use for comparison. Lambda functions are perfect for this because you can define this key-extraction logic right where you need it, without defining a whole separate function.

Python sort() using Lambda
This image illustrates how a lambda function passed to the `key` parameter of `.sort()` is used to specify the value for comparison for each element in the list.

Let's start with a simple example. Suppose you have a list of strings and want to sort them by their length instead of alphabetically.

fruits = ["fig", "pineapple", "blueberry", "apple"]

# Sort by length using a lambda function as the key
sorted_by_length = sorted(fruits, key=lambda fruit: len(fruit))

print(sorted_by_length)
# Output: ['fig', 'apple', 'pineapple', 'blueberry']

Here, for each fruit in the list, the lambda function lambda fruit: len(fruit) is called. It returns the length of the fruit's name, and this length is what Python uses to sort the elements.

Test your understanding!

You are given a list of tuples, where each tuple represents a point (x, y). Sort this list based on the y-coordinate of each point in ascending order.

points = [(4, 1), (1, 3), (5, 0), (2, 2)]

Show answer
points = [(4, 1), (1, 3), (5, 0), (2, 2)]
sorted_points = sorted(points, key=lambda point: point[1])
# Result: [(5, 0), (4, 1), (2, 2), (1, 3)]

The lambda function lambda point: point[1] extracts the second element (the y-coordinate) from each tuple, which is then used for sorting.


3. Sorting Complex Data Structures

In competitive programming, you often deal with data that's more complex than a simple list of numbers or strings. You might have lists of lists, lists of dictionaries, or lists of custom objects. Lambda functions make sorting these structures trivial.

The following video demonstrates how to apply this technique to sort lists of strings by surname, lists of tuples, and even lists of custom objects by their attributes.

How to Use Python Lambda With the Sort Method

This video from Real Python, "How to Use Python Lambda With the Sort Method," covers several practical examples of using lambda as a custom comparator.

Please watch the following segments: 01:14 - 03:13: Sorting a list of names by the surname. 04:17 - 05:11: Sorting a list of tuples (name, age) by age. 05:11 - 07:26: Sorting a list of custom Person objects by their attributes (age or name).

Sorting Lists of Dictionaries

Let's reinforce the concept of sorting complex data with a text-based resource. Dictionaries are a common way to structure data in problems.

How to use a lambda function for custom sorting in Python

The following article, "How to use a lambda function for custom sorting in Python," provides excellent code examples. Let's focus on the section about sorting a list of dictionaries.

Find the section 'Advanced Sorting Techniques' and read the subsection titled 'Sorting Dictionaries'. Notice how the lambda function uses square bracket notation (e.g., product['price']) to access the value that will be used as the sorting key.


4. Multi-Level Sorting

What if you need to sort by one criterion, and then break ties using a second criterion? For example, sorting a list of players by score (highest first), and then by name (alphabetically) for players with the same score.

You can achieve this by having the lambda function return a tuple. Python automatically sorts tuples by comparing their elements from left to right. The first element of the tuple is the primary sorting key, the second is the secondary key, and so on.

players = [
    {'name': 'Alice', 'score': 95},
    {'name': 'Bob', 'score': 100},
    {'name': 'Charlie', 'score': 95}
]

# Sort by score (desc) then name (asc)
# We negate the score to sort in descending order
sorted_players = sorted(players, key=lambda p: (-p['score'], p['name']))

print(sorted_players)
# Output:
# [{'name': 'Bob', 'score': 100}, 
#  {'name': 'Alice', 'score': 95}, 
#  {'name': 'Charlie', 'score': 95}]

Notice how Alice comes before Charlie in the output because 'Alice' comes before 'Charlie' alphabetically, even though their scores are tied.

The following resource provides a clear explanation and example of this powerful technique.

How to use a lambda function for custom sorting in Python

Let's return to the same article to see how multi-level sorting is implemented. This is a crucial pattern for many competitive programming problems.

In the 'Advanced Sorting Techniques' section, read the 'Multi-Level Sorting' subsection. Pay close attention to how a tuple (grade_priority[student['grade']], student['age']) is returned by the lambda to define multiple sorting criteria.


5. Other Uses: map and filter

While our primary focus is sorting, it's worth knowing that lambda functions are also commonly used with other built-in functions like map (to apply a function to every item of an iterable) and filter (to select items that meet a condition).

This gives you an alternative to the list comprehensions we learned in the last lesson.

  • Using map: list(map(lambda x: x * 2, numbers))
  • Using filter: list(filter(lambda x: x % 2 == 0, numbers))

The following short video provides a quick demonstration.

Python Lambda Functions Explained

To round out your understanding, this clip from Tech With Tim shows how lambdas are used with map and filter.

Watch from 02:02 to 04:12. This will give you a good sense of how versatile lambda functions are.


Conclusion

You've now added another essential tool to your Python arsenal for competitive programming. Lambda functions allow you to write short, powerful, and highly specific logic right where it's needed, particularly for custom sorting.

Key Takeaways:

  • Lambda functions are single-line, anonymous functions defined with the syntax lambda arguments: expression.
  • Their primary use is as an inline function passed as an argument to higher-order functions like sorted(), map(), and filter().
  • For sorting, they provide a clean way to specify a custom comparison key via the key parameter.
  • Multi-level sorting can be easily achieved by returning a tuple from the lambda function, defining primary, secondary, and further sorting criteria.

As you solve more problems, you'll find yourself reaching for lambda functions almost instinctively whenever you need to sort data in a non-standard way.

Up Next: In our next lesson, we will begin exploring specialized data structures from Python's collections module. We'll start with collections.deque, a high-performance, double-ended queue that is perfect for implementing efficient stacks and queues—fundamental building blocks for many algorithms.