Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Lambda Functions | Higher-Order Functions and Lambdas
Functional Programming Concepts in Python

bookLambda Functions

Swipe to show menu

Lambda functions are a core feature of Python that allow you to create small, anonymous functions using a concise syntax. The main purpose of a lambda function is to define a function in a single line, typically for short, one-off use cases where a full function definition using def would be unnecessarily verbose.

Lambda functions are most often used in combination with higher-order functions like map, filter, and sorted, where you need to pass a function as an argument but do not want to define a full function elsewhere in your code.

A lambda function can take any number of arguments but must contain only a single expression. The result of this expression is automatically returned. While lambda functions are useful for creating quick, throwaway functions, they have limitations: they cannot contain multiple statements, assignments, or complex logic, and they are less readable if overused. Because of these constraints, you should use lambda functions for simple tasks and prefer regular functions for more complex operations.

123
numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x ** 2, numbers)) print(squared)
copy

The code above uses a lambda function with the map higher-order function to square each number in the numbers list. The lambda x: x ** 2 defines an anonymous function that takes a single argument x and returns its square. This approach allows you to quickly apply a simple operation to every element in a list without defining a separate named function, making your code more concise and focused when you only need the function once.

123
numbers = [1, 2, 3, 4, 5, 6] evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens)
copy

This example uses a lambda function with filter to extract only the even numbers from the numbers list. Using a lambda function here makes the filtering logic concise and readable, especially when you only need to perform a simple check without creating a separate named function.

1. What is the main difference between a lambda function and a regular function?

2. When should you use a lambda function instead of def?

question mark

What is the main difference between a lambda function and a regular function?

Select the correct answer

question mark

When should you use a lambda function instead of def?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 5

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 2. Chapter 5
some-alt