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

Lambda Functions

Svep för att visa menyn

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)

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)

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?

Vänligen välj det korrekta svaret

question mark

When should you use a lambda function instead of def?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 5

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 2. Kapitel 5
some-alt