Course Outline (Part 19)

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.


1. lambda syntax

The syntax of a lambda function is: lambda arguments : expression

The expression is executed and the result is automatically returned.

# Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5)) # Outputs 15

2. lambda with single & multiple arguments

Lambda functions can take any number of arguments.

Single Argument:

square = lambda x : x * x
print(square(5)) # Outputs 25

Multiple Arguments:

# Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6)) # Outputs 30

# Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2)) # Outputs 13

3. lambda inside functions

The power of lambda is better shown when you use them as an anonymous function inside another function.

Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:

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

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11)) # Outputs 22
print(mytripler(11)) # Outputs 33

In this example, myfunc acts as a function factory that creates new functions.


4. Use with map(), filter(), reduce()

Lambda functions are frequently used with built-in higher-order functions like map(), filter(), and reduce().

map()

The map() function applies a given function to all items in an iterable (like a list) and returns an iterator.

numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25]

filter()

The filter() function constructs an iterator from elements of an iterable for which a function returns True.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6, 8, 10]

reduce()

The reduce() function applies a rolling computation to sequential pairs of values in a list. It must be imported from the functools module.

from functools import reduce

numbers = [1, 2, 3, 4, 5]
# Calculate the product of all numbers
product = reduce(lambda x, y: x * y, numbers)
print(product) # 120 (1*2*3*4*5)

Discussion

Loading comments...