Python Lambda Function



A lambda function is a single expression function in python. An anonymous function in Python is a function that is defined without a name.

By now we probably have defined functions in Python using the def keyword, anonymous functions are defined using the lambda keyword.

The difference is that lambda functions are anonymous. Meaning, they are functions that do not need to be named.


Syntax

lambda arguments : expression

First, we will see the normal function

Example

# Normal Function
def add(a):
    return a**2

print(add(3))

# Lambda Function
add = lambda a: a**2

print(add(3))

Output

9
9

Multiple arguments with a lambda function


Example

# Normal Function
def add(a, b):
    return a + b

print(add(3, 4))

# Lambda Function
add = lambda a, b: a + b
print(add(3, 4))

Output

7
7

Why use Python lambda functions?

The main role of the lambda function is better described in the scenarios when we use them anonymously inside another function.

In python, the lambda function can be used as an argument to the higher-order functions as arguments.


Example

def table(n):
    return lambda a: a * n


num = int(input("Enter a Number "))
myFunc = table(num)

for i in range(1, 11):
    print(num, "X", i, "=", myFunc(i))

Output

Enter a Number 2
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20

Python lambda (Anonymous Functions) | map, filter, reduce

The Python core library has three methods called map()filter(), and reduce().


1. map()

map(func, seq), transforms each element with the function.


Example

myList1 = [1, 2, 3, 4, 5, 6]

# using map function
myList2 = list(map(lambda x: x * 2, myList1))

# using list comprehension
myList3 = [x * 2 for x in myList1]

print(myList2)
print(myList3)

Output

[2, 4, 6, 8, 10, 12]
[2, 4, 6, 8, 10, 12]

2. filter()

The filter() function is similar to the map().

filter(func, seq), returns all elements for which function evaluates to True.


Example

myList1 = [1, 2, 3, 4, 5, 6]

# using filter function
myList2 = list(filter(lambda x: (x % 2 == 0), myList1))

# using list comprehension
myList3 = [x for x in myList1 if x % 2 == 0]

print(myList2)
print(myList3)

Output

[2, 4, 6]
[2, 4, 6]

3. reduce()

reduce(func, seq), frequently applies the function to the elements and returns a single value. 

This function takes 2 arguments.


Example

Average of list all items.

from functools import reduce


def average(a, b):
    return a + b


myList = [1, 2, 3, 4, 5]
res = reduce(average, myList)/len(myList)
print(res)

Output

3.0