Lambda Functions in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will learn how to use lambda functions in Python. We will begin by understanding the concept of anonymous functions and the lambda keyword, comparing them to traditional function definitions. You will then create simple lambda functions with varying numbers of parameters.

The lab will further explore how to effectively use lambda functions with built-in Python functions like sorted. Finally, we will discuss best practices for using lambda functions to ensure your code is readable and maintainable.

Understand Anonymous Functions and Lambda

In this step, we will introduce the concept of anonymous functions in Python, focusing on the lambda keyword. Anonymous functions are functions without a name, offering a concise way to define simple, single-expression functions.

In Python, we typically define functions using the def keyword. For example, a function that doubles a number looks like this:

def double(x):
    return x * 2

print(double(10))

For small functions like this, lambda provides a more compact syntax. Let's create the same function using lambda.

In the WebIDE file explorer on the left, find and open the file ~/project/lambda_example1.py. Add the following code to it:

## Define a lambda function to double a number
double_lambda = lambda x: x * 2

## Call the lambda function and print the result
print(double_lambda(10))

The syntax is lambda arguments: expression. The arguments are the inputs, and the expression is a single operation that is evaluated and returned. Notice there is no return keyword; the return is implicit.

Save the file. To run the script, open the terminal in the WebIDE and execute the following command:

python3 ~/project/lambda_example1.py

You should see the output in the terminal.

20

This demonstrates how a lambda function can be assigned to a variable and called just like a regular function.

Create Lambda Functions with Varied Parameters

Lambda functions are flexible and can be defined with zero, one, or multiple parameters. However, they are always restricted to a single expression. In this step, we will explore creating lambdas with different numbers of parameters.

First, let's create a lambda function that takes no arguments. This can be useful for defining a constant or a simple, repeatable action.

Open the file ~/project/lambda_example2.py from the file explorer. Add the following code:

## Define a lambda function with no arguments
get_greeting = lambda: "Hello, World!"

## Call the lambda function and print the result
print(get_greeting())

Next, let's create a lambda function that accepts multiple arguments. We will define a lambda that adds two numbers. Add this code to the same lambda_example2.py file:

## Define a lambda function that adds two numbers
add_numbers = lambda x, y: x + y

## Call the lambda function with two arguments and print the result
print(add_numbers(5, 3))

Save the file. Now, run the script from the terminal to see both outputs:

python3 ~/project/lambda_example2.py

The terminal will display the results from both lambda functions.

Hello, World!
8

This shows that lambda functions can handle different parameter configurations, making them versatile for various simple tasks.

Use Lambda with the sorted() Function

One of the most common use cases for lambda functions is to serve as a quick, inline function for higher-order functions (functions that take other functions as arguments). A prime example is Python's built-in sorted() function, which can accept a key argument. The key specifies a function to be called on each element before making sorting comparisons.

Imagine you have a list of tuples, where each tuple represents a product and its price. You want to sort this list based on the price.

Open the file ~/project/lambda_sorted.py in the editor. Add the following code:

## A list of tuples (product, price)
products = [('Laptop', 1200), ('Mouse', 25), ('Keyboard', 75)]

## Sort the list by price (the second element of each tuple) using a lambda function
sorted_products = sorted(products, key=lambda item: item[1])

## Print the sorted list
print(sorted_products)

In this code, key=lambda item: item[1] tells sorted() to use the second element (item[1], which is the price) of each tuple as the value for sorting. This is much more concise than defining a separate function with def.

Save the file and run it from the terminal:

python3 ~/project/lambda_sorted.py

You will see the list of products sorted by price in ascending order.

[('Mouse', 25), ('Keyboard', 75), ('Laptop', 1200)]

This pattern is extremely common and useful for sorting complex data structures in a simple and readable way.

Advanced Lambda Techniques

In this step, we will explore some slightly more advanced ways to use lambda functions, including setting default parameter values and immediately invoking a lambda function.

Like regular functions, lambda functions can have parameters with default values. This provides a fallback value if an argument is not supplied during the function call.

Open the file ~/project/lambda_advanced.py in the editor. Add the following code:

## Define a lambda function with a default parameter value
power = lambda base, exponent=2: base ** exponent

## Call the lambda function without the optional argument (uses default)
print(power(3))

## Call the lambda function with both arguments
print(power(3, 3))

Another interesting technique is to define and immediately call a lambda function. This is known as an Immediately Invoked Function Expression (IIFE). It can be useful for creating a temporary, single-use function to compute a value without cluttering the namespace.

Add the following code to the lambda_advanced.py file:

## Define and immediately invoke a lambda function to calculate a discounted price
price = 100
discount_percentage = 20
final_price = (lambda p, d: p * (1 - d / 100))(price, discount_percentage)

print(final_price)

Save the file and run it from the terminal:

python3 ~/project/lambda_advanced.py

The output will show the results of both examples.

9
27
80.0

While these techniques demonstrate the flexibility of lambdas, remember that readability is key. If the logic becomes complex, a standard def function is often a better choice.

Best Practices and Readability

In this final step, we will discuss best practices for using lambda functions. While lambdas are a powerful tool for writing concise code, they should be used judiciously to maintain readability and maintainability.

When to use lambda:

  • As arguments to higher-order functions: This is the primary use case. Functions like sorted(), map(), and filter() are perfect candidates for lambdas.
  • Simple, short operations: If the logic fits comfortably and clearly on one line, a lambda is a good choice.

When to avoid lambda:

  • Complex logic: If you need multiple statements, complex conditional logic, or loops, always use a def function.
  • Readability concerns: If a lambda expression is difficult to understand at a glance, it defeats its purpose. A named function with a descriptive name is better.
  • Reusability: If you need the same logic in multiple places, define it once with def to follow the Don't Repeat Yourself (DRY) principle.

Let's look at a good, readable example that reinforces the best-practice use case. Open the file ~/project/lambda_best_practice.py and add the following code:

## A list of dictionaries
students = [
    {'name': 'Alice', 'grade': 88},
    {'name': 'Bob', 'grade': 95},
    {'name': 'Charlie', 'grade': 72}
]

## A good use of lambda: sorting a list of dictionaries by a value
sorted_by_grade = sorted(students, key=lambda student: student['grade'])

print("Sorted by grade:", sorted_by_grade)

## For comparison, a more complex task is better with a named function.
## For example, if you needed to apply a curve and check for a minimum score,
## a 'def' function would be much clearer than a complex lambda.
def process_grade(student):
    curved_grade = student['grade'] * 1.05
    return max(curved_grade, 75) ## Ensure a minimum score

processed_grades = [process_grade(s) for s in students]
print("Processed grades:", processed_grades)

Save the file and run it:

python3 ~/project/lambda_best_practice.py

You will see the output:

Sorted by grade: [{'name': 'Charlie', 'grade': 72}, {'name': 'Alice', 'grade': 88}, {'name': 'Bob', 'grade': 95}]
Processed grades: [92.4, 99.75, 75.60000000000001]

The first part shows a clear and appropriate use of lambda. The second part illustrates a scenario where a named function is more suitable. Always prioritize writing code that is easy for you and others to read and understand.

Summary

In this lab, you learned the fundamentals of Python's lambda functions. You started by understanding their syntax and how they differ from standard functions defined with def. You practiced creating lambdas with zero, one, and multiple parameters, and saw how they can be assigned to variables and called.

A key takeaway was the practical application of lambda functions as arguments for higher-order functions, particularly with sorted() to define custom sorting logic concisely. We also explored advanced techniques like default parameters and immediately invoked function expressions (IIFE). Finally, you reviewed best practices for using lambdas, emphasizing that while they are powerful for simple, single-use cases, readability and maintainability should always be the priority, favoring named functions for more complex logic.