DEV Community

Max
Max

Posted on • Updated on

Python Lambda Function Tutorial

Python lambda function is a small anonymous function that can have any number of arguments but can only have one expression. It is defined using the keyword lambda followed by the parameters and the expression. Lambda functions are often used for short and simple operations that do not require a separate function definition.

Lambda Function Syntax

lambda argument1,..,argumentN: expression
Enter fullscreen mode Exit fullscreen mode

Simple lambda function

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

add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
Enter fullscreen mode Exit fullscreen mode

In this example, the lambda function add takes two arguments x and y, and returns their sum.

Python Lambda Function using map and filter

Lambda function in a filter()

Here is an example of using a lambda function with the filter() function to filter out even numbers from a list:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Lambda function in a map()

Here is an example of using a lambda function with the map() function to square each element of a list:

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
Enter fullscreen mode Exit fullscreen mode

Explore Other Related Articles

Python If, If-Else Statements Tutorial
Python Function Tutorial
Python break and continue tutorial
Python While Loop tutorial
Python For Loops, Range, Enumerate Tutorial

Top comments (1)

Collapse
 
devtonic profile image
Vlad Andrei

Amazing, this are the examples Chat GPT gives you if you ask it to explain the lambda function. Guess you're pretty lazy, aren't you, Max?