Python Lambda Function

What is Lambda Function?

A lambda function is an in-line function that does not have a name.

It is often known as anonymous function.

lambda function works exactly the same as normal function except one difference: lambda contains only a single expression

Syntax

Here’s the syntax of a lambda expression:

Python lambda Function Syntax

Basic Example

Here is a basic example of a function that doubles the passed value.

Example:

def doubler(x):
    return x*2

print(doubler(2))    # 4
print(doubler(5))    # 10

You can achieve the same result with a lambda function.

Example:

doubler = lambda x: x*2

print(doubler(2))    # 4
print(doubler(5))    # 10

Multiple Arguments

You can send as many arguments as you like to a lambda function; just separate them with a comma ,.

Example: A lambda function that multiplies two values

mul = lambda x, y: x*y
print(mul(2, 5))    # 10

Example: A lambda function that adds three values

add = lambda x, y, z: x+y+z
print(add(2, 5, 10))    # 17

Default Argument Value

You can assign a default value to an argument.

So, when you call the lambda function without argument, it uses the default value.

Example: A lambda function that increments value by 1 by default

incrementer = lambda x, y=1: x+y
print(incrementer(5, 3))	# 8

# using default
print(incrementer(5))		# 6

Return Multiple Values

To return multiple values pack them in a tuple.

Then use multiple assignment to unpack the parts of the returned tuple.

Example: Return multiple values by packing them in a tuple

findSquareCube = lambda num: (num**2, num**3)
x, y = findSquareCube(2)
print(x)  # 4
print(y)  # 8

if else in a Lambda

To implement selection logic in a lambda, you can use the if else ternary expression.

Example: A lambda function that returns the smallest item

findMin = lambda x, y: x if x < y else y

print(findMin(2, 4))      # 2
print(findMin('a', 'x'))  # a

map() with a Lambda

A lambda function can be used with the map() function to create more concise code.

The map() function applies the given function on every item of iterable and returns a list.

Example: Double each item of the list

L = [1, 2, 3, 4, 5, 6]
double = map(lambda x: x*2, L)
print(double)  # [2, 4, 6, 8, 10, 12]

filter() with a Lambda

A lambda function can also be used with filter() function to filter items of an iterable.

The filter() function creates a list where the items are filtered through a function to test if the item is accepted or not.

Example: Filter the values above 18

age = [5, 11, 16, 19, 24, 42]
adults = filter(lambda x: x > 18, age)
print(adults)	# [19, 24, 42]

List Comprehension in a Lambda

You can even use list comprehension in a lambda function.

Example: Flatten a nested list with lambda

flatten = lambda l: [item for sublist in l for item in sublist]

L = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
print(flatten(L))	# [1, 2, 3, 4, 5, 6, 7, 8, 9]

L = [['a', 'b', 'c'], ['d', 'e']]
print(flatten(L))	# ['a', 'b', 'c', 'd', 'e']

Sort With a lambda

A lambda function can be used with sorted() function to sort an iterable.

Example: Sort a list of tuples based on age of students

L = [('Sam', 35),
    ('Max', 25),
    ('Bob', 30)]
x = sorted(L, key=lambda student: student[1])
print(x)	# [('Max', 25), ('Bob', 30), ('Sam', 35)]

Nested Lambdas

Like normal functions, lambdas can be nested too.

Example: Nested Lambdas

multiplier = (lambda x: (lambda y: x*y))

doubler = multiplier(2)
print(doubler(10))    # 20

tripler = multiplier(3)
print(tripler(10))    # 30

Jump Tables

lambda is also commonly used to implement jump tables.

Jump tables are lists or dictionaries of functions to be called on demand.

Example: Create jump table of square and cube in python

# dictionary of functions
exponent = {'square':lambda x: x ** 2,
            'cube':lambda x: x ** 3}

print(exponent['square'](3))    # 9
print(exponent['cube'](3))      # 27
# list of functions
exponent = [lambda x: x ** 2,
            lambda x: x ** 3]

print(exponent[0](3))   # 9
print(exponent[1](3))   # 27