Перейти к основному содержимому

Python Lambda Functions: A Beginner’s Guide

Learn about Python lambda functions, their purpose, and when to use them. Includes practical examples and best practices for effective implementation.
· 10 мин читать

Исследуйте с ИИ

Lambda functions in Python are powerful, concise tools for creating small, anonymous functions on the fly. They are perfect for simplifying short-term tasks, streamlining code with higher-order functions like map, filter, or sorted, and reducing clutter when defining temporary or throwaway logic. They also offer an elegant solution for improving code readability in simple scenarios. This article will explore what lambda functions are, their characteristics, and how to use them effectively.

In this guide, we’ll provide a complete guide to lambda functions in Python, covering their mechanics, syntax, and how they compare to standard functions, with simple examples to illustrate key concepts.We explore common use cases, such as using lambda functions within functional programming paradigms and their efficiency relative to standard functions.. Practical examples and best practices are included to help you effectively incorporate lambda functions into your Python programming.

What is a Lambda Function in Python?

Lambda functions differ from standard Python functions in several key ways. They are anonymous expressions, meaning they have no name unless explicitly assigned to a variable. They are also more concise and defined in a single line without the need for a return statement. This makes them ideal for simple, one-time operations and for use as inline arguments in higher-order functions like map, filter, and sorted.

Here is an example of a lambda function that adds two numbers:

fn = lambda x, y: x + y
print(fn)

# <function <lambda> at 0xe508b8>

How lambda functions work

How does this lambda function work? To understand it, let's compare it to a standard Python function.

# Example: add two numbers using standard Python function
def add_numbers(x, y):
    return x + y

This standard function is straightforward. The def keyword defines the function, which takes two arguments, x and y. It calculates the sum of x and y and returns the result.

Now, let’s see how our lambda function achieves the same task.

# Example: add two numbers using a lambda function
fn = lambda x, y: x + y
print(fn)

# <function <lambda> at 0xbfb968>

The lambda keyword signifies that we are defining a lambda function, eliminating the need for the def keyword. Following this lambda keyword, the input arguments x and y are listed. After the colon, we specify the expression whose result will be returned, x + y.

Writing Lambda Functions in Python: Examples

To help you get to grips with the concepts we’ve explored so far, let’s look at a few examples of how Lambda functions work in Python. 

Step-by-step guide to writing lambda functions

Lambda functions are ideal for creating short, straightforward functions without extra complexity. 

For example, suppose you want to check if a given non-zero integer is even. You could write a standard Python function, but the same functionality can be achieved with a concise one-liner lambda function assigned to a variable: is_even = lambda x: x % 2 == 0. 

Here, the lambda function on the right side of the assignment takes an input x and returns True if x is even (that is if the remainder when divided by 2 is 0). 

This lambda function is then assigned to the variable is_even, allowing it to be called like a regular function. For instance, is_even(5) (returns False) and is_even(678432) (returns True).

Lambda functions are also great for defining simple formulas. For instance, to convert Celsius to Fahrenheit, you could use a lambda function: c_to_f = lambda c: (c * 9/5) + 32. You then call the function like any other function: c_to_f(0).

Common use cases for lambda functions

Lambda functions are often used in functional programming, particularly with functions like map() and filter(), which take other functions as arguments to process elements in a collection. Let's see how to use a lambda function with filter(). Here's a code snippet:

# Use filter with lambda function
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))  # print the list of the filter object to see the result

# [2, 4, 6, 8]

In this code, we start by defining a set of numbers. Next, we create a lambda function to check if a number is even. The filter function applies this lambda function to the numbers set. We then print the list of even numbers identified by the filter function.

Similarly, we can use the map function to apply a lambda to a collection of elements. In the example below, we calculate the lengths of strings in a list by mapping the len() function to each element.

# Use map with lambda function
fruits = ['apple', 'banana', 'cherry']
lengths = list(map(lambda x: len(x), fruits))
print(lengths)

# [5, 6, 6]

Lambda function are also used with the sorted() function, which sorts the elements of a collection to return a new collection. In the following example (without a lambda), we use the sorted() function to sort a list of numbers.

numbers = [1, 10, -1, 3, -10, 5]
sorted_stuff = sorted(numbers)
print(sorted_stuff)

# [-10, -1, 1, 3, 5, 10]

Suppose we wanted to sort the list of numbers by absolute value. How would we achieve this? The sorted() function includes a key argument that allows us to customize the sorting order by providing a lambda function.

# Sort according to absolute value
sorted_numbers_absolute = sorted(numbers, key=lambda x: abs(x))
print(sorted_numbers_absolute)

# [1, -1, 3, 5, 10, -10]

Another use case for sort() with a lambda function is to sort a list of tuples based on a specific element, say the second one.

# Sort a list of tuples by the second element
data = [(1, 3), (2, 1), (4, 2)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)

# [(2, 1), (4, 2), (1, 3)]

In this code snippet, we define data as a list of tuples. We then use the sorted() function with the key parameter, where a lambda function extracts the second element of each tuple for sorting.

Are Lambda Functions Faster in Python?

In Python, lambda functions are not inherently faster than standard functions, as both are compiled to similar bytecode. However, they can slightly reduce overhead in cases where defining a full function would add unnecessary boilerplate.

Here are a few test cases comparing lambda functions to standard Python functions. The code was executed on my laptop, a MacBook Pro with an Apple M1 Pro chip, 16 GB of memory, running macOS Sequoia 15.2.

Lambda functions can be used inline as anonymous functions when passed directly to higher-order functions like map(), filter(), or sorted(). This avoids the need to define and reference a separate named function, reducing both boilerplate code and lookup overhead.

import time

numbers = list(range(1, 1000000))

# Standard function
def double_standard(x):
    return x * 2

start = time.time()
map(double_standard, numbers)
print(time.time() - start)

# Lambda function
double_lambda = map(lambda x: x * 2, numbers)

start = time.time()
list(map(lambda x: x * 2, numbers))
print(time.time() - start)

# 3.504753112792969e-05
# 2.384185791015625e-05

Lambda functions are ideal for one-time or temporary use, as they eliminate the need for a formal def block, saving both time and space. In the following code block, we compare the performance of a standard function to that of a lambda function. We sort a dictionary with a million elements, where the keys are random two-letter codes, and the values are random integers.

import random
import string

# Generate a dictionary with elements of the form 'XX': number.
NUMBER_ITEMS = 1000000
items = {
    ''.join(random.choices(string.ascii_uppercase, k=2)): random.randint(1, 100)
    for _ in range(NUMBER_ITEMS)
}

# Standard function (extra definition step)
def sort_standard(item):
    return item[1]

print('Standard')
start = time.time()
sorted_items_standard = sorted(items, key=sort_standard)
print(time.time() - start)
print(sorted_items_standard[:5])
print()

# Lambda function
print('Lambda')
start = time.time()
sorted_items_lambda = sorted(items, key=lambda x: x[1])
print(time.time() - start)
print(sorted_items_lambda[:5])
print()

# Standard
# 0.00011610984802246094
# ['OA', 'VA', 'XA', 'IA', 'BA']
# Lambda
# 0.00011014938354492188
# ['OA', 'VA', 'XA', 'IA', 'BA']

Python Lambda Functions: Examples and Practice

Let’s work through some more practical examples to showcase how Lambda functions work in Python. 

Practical examples

Lambda functions are often used with built-in Python methods. For instance, let's look at using reduce() to apply a user-defined binary function cumulatively to the items of a sequence.

# Example: Use lambda function with built-in Python method reduce.
from functools import reduce

numbers = [5, -6, 2, 7]
total = reduce(lambda x, y: x + y, numbers)
print(f'The sum of the numbers is {total}.')

# The sum of the numbers is 8.

Similar to filter() or map() above, reduce() applies a function, here given by a lambda, to a set of elements.

Now, let’s explore another built-in Python function, zip(). The zip function pairs corresponding elements from multiple lists into tuples. For example, the result of zip(['a', 'b', 'c'], [1, 2, 3]) is [('a', 1), ('b', 2), ('c', 3)].

# Example: Use lambda function with built-in Python method zip.
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Using zip and a lambda function to multiply corresponding elements
result = list(map(lambda x: x[0] * x[1], zip(list1, list2)))

print(f'The result of multiplying corresponding elements is {result}.')

# The result of multiplying corresponding elements is [4, 10, 18].

This code calculates the product of corresponding elements from two lists, list1 and list2. It uses zip() to pair elements from the lists into tuples, then applies a lambda function with map() to multiply the paired elements, and finally converts the result into a list.

Real-world example: data transformation

Let’s imagine you run a fruit stand and want to compute the total sales amount for each type of fruit.

First, we create some sales records. Then, we use map() with a lambda function to compute total_sales by multiplying the price and quantity for each item in the sales_data dictionary. The **record syntax unpacks the original dictionary, ensuring that all its keys and values are preserved in the new dictionary. Finally, we print out each record of the transformed data.

# Sample data: list of dictionaries representing sales records
sales_data = [
	{'fruit': 'peaches', 'price': 1.41, 'quantity': 3},
	{'fruit': 'pears', 'price': 1.21, 'quantity': 2},
	{'fruit': 'mangoes', 'price': 0.56, 'quantity': 3},
]

# Using a lambda function to calculate total sales for each record
transformed_data = list(
	map(
		lambda entry: {**entry, 'total_sales': round(entry['price'] * entry['quantity'], 2)},
		sales_data
	)
)

# Print the transformed data
for record in transformed_data:
	print(record)

# {'fruit': 'peaches', 'price': 1.41, 'quantity': 3, 'total_sales': 4.23}
# {'fruit': 'pears', 'price': 1.21, 'quantity': 2, 'total_sales': 2.42}
# {'fruit': 'mangoes', 'price': 0.56, 'quantity': 3, 'total_sales': 1.68}

Simple problems for users to solve with lambda functions

If you'd like to practice using lambda functions, here are some problems to try.

  • Given a number, find its square.
  • Given two numbers, find the larger one.
  • Given a number, check if it is odd.
  • Given a list of positive integers, filter out all the odd numbers.
  • Sort a list of 3-element tuples using their third elements.
  • Extract the domain from an email address. For example, given [email protected], extract example.com.

Let's look at some common mistakes programmers make with lambdas and some fixes.

1. The first mistake is to use a lambda function when it's inappropriate. It’s important to remember that lambda functions are designed for short, simple tasks, not for handling complex logic. For example, the following code snippet is not an ideal use case for a lambda function.

# Complex logic in a lambda
result = lambda x: (x ** 2 + x - 1) / (x + 1 if x != -1 else 1)
print(result