Python Lambda Function

In Python, a lambda function is a small anonymous function that can take any number of arguments, but can only have one expression. It is typically used to define a function inline, and it is often used as a callback function or in places where a function is expected as an argument.

Here is the syntax for defining a lambda function in Python:

lambda arguments: expression

Here is an example of a lambda function that takes two arguments and returns their sum:

>>> sum = lambda x, y: x + y
>>> sum(3, 4)
7

Lambda functions can be used anywhere that a function is expected, such as in a function call or in a list comprehension. For example:

>>> numbers = [1, 2, 3, 4, 5]
>>> even_numbers = filter(lambda x: x % 2 == 0, numbers)
>>> even_numbers
[2, 4]

In this example, the filter function takes a lambda function that returns True if its argument is even, and a list of numbers. It returns a new list containing only the even numbers from the original list. I hope this helps! Let me know if you have any questions.

Was this helpful?
[0]