Python Lambda – How to Create Lambda Functions

This tutorial walks you through the Python lambda operator a.k.a anonymous function. You’ll learn how to create a lambda function, use it with lists, dictionaries, map() and filter().

In Python, you have a couple of ways to make functions:

a) Use Def keyword: It creates a function object and assigns it to a name.

b) Use lambda: It creates an inline function and returns it as a result.

A lambda function is a lightweight anonymous function. It can accept any number of arguments but can only have a single expression.

Let’s learn more about the Python lambda.

Table of Content

What is lambda in Python?

Lambda is an unnamed function. It provides an expression form that generates function objects.

This expression form creates a function and returns its object for calling it later.

Python Lambda - Use with map, filter, reduce

TOC

How to create a lambda function?

Syntax

It has the following signature:

lambda arg1, arg2, ... argN: expression using arguments

The body of a lambda function is akin to what you put in a def body’s return statement. The difference here is that the result is a typed-expression, instead of explicitly returning it.

Please note that a lambda function can’t include any statements. It only returns a function object which you can assign to any variable.

The lambda statement can appear in places where the def is not allowed. For example – inside a list literal or a function call’s arguments, etc.

Example

lambda inside a list :

alist = [lambda m:m**2, lambda m,n:m*n, lambda m:m**4]

print(alist[0](10), alist[1](2, 20), alist[2](3)) # Output: 100 40 81

lambda inside a dictionary :

key = 'm'

aDict = {'m': lambda x:2*x, 'n': lambda x:3*x}

print(aDict[key](9)) # Output: 18

TOC

Extending Python lambda functions

We can extend the utility of lambda functions by using it with the filter and map functions.

It is possible by passing the lambda expression as an argument to another function. We refer to these methods as higher-order functions as they accept function objects as arguments.

Python provides two built-in functions like filter(), map() which can receive lambda functions as arguments.

Map functions over iterables – map()

The map() function lets us call a function on a collection or group of iterables.

We can also specify a Python lambda function in the map call as the function object.

The map() function has the following signature.

map(function_object, iterable1, iterable2,...)

It expects variable-length arguments: first is the lambda function object, and rest are the iterables such a list, dictionary, etc.

What does the map() function do?

The map function iterates all the lists (or dictionaries etc.) and calls the lambda function for each of their element.

What does the map() function return?

The output of map() is a list which contains the result returned by the lambda function for each item it gets called.

Below is a simple example illustrating the use of map() function to convert elements of lists into uppercase.

# Python lambda demo to use map() for adding elements of two lists

alist = ['learn', 'python', 'step', 'by', 'step']

output = list(map(lambda x: x.upper() , alist))

# Output: ['LEARN', 'PYTHON', 'STEP', 'BY', 'STEP']
print(output)

Let’s have another example illustrating the use of map() function for adding elements of two lists.

# Python lambda demo to use map() for adding elements of two lists

list1 = [1, 2, 3, 4]
list2 = [100, 200, 300, 400]

output = list(map(lambda x, y: x+y , list1, list2))

# Output: [101, 202, 303, 404]
print(output)

TOC

Select items in iterables – filter()

The filter() function selects an iterable’s (a list, dictionary, etc.) items based on a test function.

We can also filter a list by using the Python lambda function as the function object.

The filter function has the following signature.

filter(function_object, list)

It expects two parameters: first is the lambda function object and the second is a list.

What does the filter() function do?

The filter function iterates the list and calls the lambda function for each element.

What does the filter() function return?

It returns a final list containing items for which the lambda function evaluates to True.

Below is a simple example illustrating the use of filter() function to determine vowels from the list of alphabets.

# Python lambda demo to filter out vowles from a list

alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
vowels = ['a', 'e', 'i', 'o', 'u']

output = list(filter(lambda x: (x in vowels) , alphabets))

# Output: ['a', 'e', 'i']
print(output)

TOC

Aggregate items in iterables – reduce()

The reduce method continuously applies a function on an iterable (such as a list) until there are no items left in the list. It produces a non-iterable result, i.e., returns a single value.

This method helps in aggregating data from a list and returning the result. It can let us do a rolling calculation over successive pairs of values in a sequence.

We can also pass a Python lambda function as an argument to the reduce method.

The reduce() function has the following syntax.

reduce(func_obj, iterable[, initializer])

Below is a simple example where the reduce() method is computing the sum of elements in a list.

from functools import reduce

def fn(m, n) : return m + n

print(reduce((lambda m, n: m + n), [1, 2, 3, 4]))
print(reduce(fn, [1, 2, 3, 4]))

After executing the above code, you see the following output.

10
10

TOC

Summary – Python lambda

Today, we covered Python Lambda. It is one of many ways to create functions in Python.

Hope you learned it well. Do try to use it in your routine programming tasks.

If you like to see more such updates, do follow us on (Facebook/Twitter).

Best,

TechBeamers