Lambda functions, also known as anonymous functions, are a feature of Python and many other programming languages. They are small, inline functions that can be defined quickly and used in places where a normal function might be cumbersome or unnecessary1.
Here’s a basic syntax of a lambda function in Python:
lambda arguments: expression
The arguments
are the inputs to the function, and the expression
is what the function computes and returns2.
Here are some examples of lambda functions:
- A lambda function that adds 10 to the number you send in:
x = lambda a: a + 10
print(x(5)) # Outputs: 15
- A lambda function that multiplies two arguments and returns the result:
x = lambda a, b: a * b
print(x(5, 6)) # Outputs: 30
- A lambda function that sums three arguments and returns the result:
x = lambda a, b, c: a + b + c
print(x(5, 6, 2)) # Outputs: 13
Lambda functions are particularly powerful when used in conjunction with functions like map()
, filter()
, and reduce()
which expect function objects as arguments1.
For example, if you want to square all numbers in a list, you can use map()
with a lambda function:
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # Outputs: [1, 4, 9, 16, 25]
Remember, while lambda functions can be useful for writing quick, short functions, they have limitations, such as only being able to contain one expression and not having a return
statement1. For more complex operations, it’s often better to define a full function with def
.
Thanks