Python Lambda
A lambda is a small function without a name (an anonymous function), written in one line with the lambda keyword. Python took this idea from functional programming.
Syntax
lambda arguments: expression
A lambda can take any number of arguments, but it can have only one expression. The value of that expression is returned automatically, so you do not write return.
Examples
add_one = lambda x: x + 1
print(add_one(1))
print((lambda x: x + 2)(1))
Output of the above program is
2
3
Here x is the argument and x + 1 is the expression. In the second line the lambda is called right away by putting brackets around it and passing the argument.
The same function written with def looks like this:
def add_one(x):
return x + 1
print(add_one(1))
Output of the above program is
2
More than one argument
multiply = lambda a, b: a * b
print(multiply(3, 4))
Output of the above program is
12
Lambda with a condition
bigger = lambda a, b: a if a > b else b
print(bigger(5, 9))
Output of the above program is
9
Note:
A lambda cannot have statements like return, loops or assignments. Read why. For longer logic, use a normal def function.
Where lambda is used
Lambdas are mostly used as a short function inside another function. Three common places are sorted(), map() and filter().
students = [("Robin", 85), ("Maria", 92), ("John", 78)]
print(sorted(students, key=lambda s: s[1]))
nums = [1, 2, 3, 4, 5]
print(list(map(lambda x: x * 2, nums)))
print(list(filter(lambda x: x % 2 == 0, nums)))
Output of the above program is
[('John', 78), ('Robin', 85), ('Maria', 92)]
[2, 4, 6, 8, 10]
[2, 4]
A function that returns a lambda
def multiplier(n):
return lambda x: x * n
double = multiplier(2)
print(double(5))
Output of the above program is
10
Lambda vs def
| Point | lambda | def |
|---|---|---|
| Name | No name needed | Has a name |
| Body | One expression | Many statements |
| Return | Automatic | Use return |
| Best for | Short, one-time use | Anything bigger or reused |
Summary
- A lambda is a one-line anonymous function:
lambda args: expression. - It returns the value of the expression automatically.
- It is handy with
sorted(),map()andfilter(). - Use
defwhen the function is long or used in many places. - Read more in the interview question What is a lambda function?
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |