A lambda function is an anonymous function in Python.
syntax → lambda <argument name> : <return expression>
It starts with the keyword, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression.
For example, lambda x, y, z: x+y+z
would calculate the sum of the three-argument values x+y+z
.
Use of Lambda Functions
- uses lambda functions once we require a nameless function for a brief period of your time.
- Lambda functions reduce the number of lines of code when compared to normal python functions.
- They are generally used when a function is needed temporarily for a short period of time
- Using the lambda function, you can define a function and call it immediately at the end of the definition. This can’t be done with def functions.
- In Python, we generally use Lambda Functions as an argument to a higher-order function (a function that takes in other functions as arguments).
For Example, These are used together with built-in functions like filter(), map(), and reduce()
Example
sequences = [10,2,8,7,5,4,11]
squared_result = map (lambda x: x*x, sequences)
print(list(squared_result))
Output → [100, 4, 64, 49, 25, 16, 121]
Note:
- Internally, both lambda and def functions work exactly the same
- Lambda functions can have 0 or 1 expression, not more.
No expression
x = lambda : "hello world"
print(x())
output → hello world
Single expression
new_single = lambda x : (x%2)
print(new_single(10))
output → 0
- Lambda functions accept all kinds of arguments, just like a normal def function.
Important Notice for college students
If you’re a college student and have skills in programming languages, Want to earn through blogging? Mail us at geekycomail@gmail.com
For more Programming related blogs Visit Us Geekycodes. Follow us on Instagram.