Anonymous functions in python (Lambda)
By: Sooraj Parakkattil
Tags: Coding, Programming, Software Development, Introduction, Python

Small anonymous functions can be created with the lambda keyword in python

Photo by Kevin Ku on Unsplash

Lambda expressions in Python and other programming languages have their roots in lambda calculus, a model of computation invented by Alonzo Church

Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope.

In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter(), map() etc.

(anonymous here just means nameless functions)

syntax:

The keyword: lambda

Arguments:

An expression

lambda arguments: expression

They are syntactically restricted to a single expression. ie, can pass any number of arguments, but can only perform one operation on them

functions are objects in python, Lambda functions can be used wherever function objects are required. ie. we can assign it to variables and use as with objects.ie,

variable = lambda arguments: expression

variable(arguments)

difference between a normal def defined function and lambda function

# Python code to illustrate cube of a number

# showing difference between def() and lambda().

def square(y):

return y*y;



g = lambda x: x*x

print(g(7))



print(cube(5))

Without using Lambda : Here, both of them returns the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword.

Here, both of them returns the cube of a given number. But, while using def, we needed to define a function with a name cube and needed to pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword. Using Lambda : Lambda definition does not include a “return” statement, it always contains an expression which is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions.

Example of Lambda Function in python

1.

# Program to show the use of lambda functions

double = lambda x: x * 2 print(double(5))

In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x * 2 is the expression that gets evaluated and returned.

This function has no name. It returns a function object which is assigned to the identifier double . We can now call it as a normal function. The statement

double = lambda x: x * 2

is nearly the same as:

def double(x):

return x * 2

2.

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

>>> pairs.sort(key=lambda pair: pair[1])

>>> pairs

[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

Example use with filter()

The filter() function in Python takes in a function and a list as arguments.

The function is called with all the items in the list and a new list is returned which contains items for which the function evaluates to True .

Here is an example use of filter() function to filter out only even numbers from a list.

# Program to filter out only the even items from a list

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

print(new_list)

Example use with map()

The map() function in Python takes in a function and a list.

The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item.

# Program to double each item in a list using map()

my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(map(lambda x: x * 2 , my_list))

print(new_list)

example with reduce

The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list. This is a part of functools module. Example:

from functools import reduce

li = [5, 8, 10, 20, 50, 100]

sum = reduce((lambda x, y: x + y), li)

print (sum)

multi-key sort using lambda

data = [[1,3,4],[1,5,6],[1,4,1],[2,4,5],[2,1,7],[2,1,2]]

data = sorted(data,key=lambda l:(l[1], l[2], l[3]), reverse=False)

print data

Or you can achieve the same using itemgetter (which is faster and avoids a Python function call)(not lambda just a bonus code):

import operator

data = sorted(data, key = operator.itemgetter(1, 2, 3))

And notice that here you can use sort instead of using sorted and then reassigning:

data.sort(key = operator.itemgetter(1, 2, 3))

suggested links:

https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions

https://realpython.com/python-lambda/

https://www.geeksforgeeks.org/python-lambda-anonymous-functions-filter-map-reduce/

https://www.programiz.com/python-programming/anonymous-function