Python Lambda Function Tutorial
Max
Posted on February 24, 2023
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
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
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]
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]
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
Posted on February 24, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.