What is lambda in Python?

In Python, a lambda function is a small, anonymous function that can have any number of arguments, but can only have one expression. Lambda functions are often used for short, simple operations that can be defined in a single line of code. They are defined using the lambda keyword, followed by the function's arguments and the expression to be evaluated.

Adds two numbers using lambda function

add = lambda x, y: x + y result = add(5, 3) # result will be 8

Lambda functions are commonly used as arguments to higher-order functions like map(), filter(), and sorted(). For instance:

numbers = [1, 5, 3, 8, 2] squared = list(map(lambda x: x ** 2, numbers)) # squared will be [1, 25, 9, 64, 4] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) # even_numbers will be [8, 2]

While lambda functions can be useful for simple operations, more complex logic is often better handled using regular named functions.

Conclusion

python lambda function

A lambda function is a concise way to create small, anonymous functions for simple operations. It allows you to define functions with a single expression and is commonly used for tasks that involve mapping, filtering, or applying simple operations to elements in lists or other data structures. Lambda functions are especially useful when you need a quick and short function definition without the need to create a full named function.