# What is lambda in Python?

Lambda, the 11th letter of the Greek alphabet , is the symbol for wavelength . Lambda comes from the Lambda Calculus and refers to anonymous functions in programming. In Python, Lambda is an expression . Lambda's body is a single expression, not a block of statements. Because it is limited to an expression, a lambda is less general than a def you can only squeeze so much logic into a lambda body without using statements such as if. This is not exactly the same as lambda in functional programming languages, but it is a very powerful concept that's well integrated into Python and is often used in conjunction with typical functional concepts like map() , filter() and reduce() . Moreover, Lambda can be used wherever function objects are required.

The general syntax of a lambda function is quite simple:

lambda argument_list: expression

The argument list consists of a comma separated list of arguments and the expression is an arithmetic expression using these arguments.

Here's an example. You can build a function in the normal way, using def, like this:

def square_root(x): return math.sqrt(x)

Using lambda:

square_root = lambda x: math.sqrt(x)
example
square_root = lambda x: x*x print(square_root(2))

Lambda allows you to write quick throw away functions without naming them. It also provides a nice way to write closures also.

example

Find the sum of two numbers using lambda

output
30

Lambda in Conditional expressions:

result = lambda x: "Bigger than 100" if x > 100 else "Smaller than 100"

print(result(99))

output
Smaller than 100

### Map example using lambda

my_list = [1, 2, 3, 4, 5, 6] squared = map(lambda x: x**2, my_list) print(list(squared))
output
[1, 4, 9, 16, 25, 36]

### Filter example using lambda

my_list = [1, 3,5, 7, 9, 11, 13, 15] new_list = list(filter(lambda x: (x%3 == 0) , my_list)) print(new_list)
output
[3, 9, 15]

### Reduce example using lambda

from functools import reduce result = reduce((lambda x, y: x * y), [1, 2, 3, 4,5]) print(result)
output
120

### Calculating the sum of the numbers from 1 to 1000 using lambda

from functools import reduce total = reduce(lambda x, y: x+y, range(1,1001)) print(total)
output
500500