Utility of Lambda function Python

Utility of Lambda function Python

When you started learning Python, one of the most confusing concepts to get your head around was the lambda statement. Not only you, we are sure that other new programmers also get confused by it as well. And some of you are probably wondering what we are talking about. So, let's find out what is Lambda function and how does it use in Python?

Lambda

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions, or used for constructing the result of a higher-order function that needs to return a function. In several programming languages, anonymous functions are introduced using the keyword lambda, and anonymous functions are often referred to as lambdas or lambda abstractions. This functions originate in the work of Alonzo Church in his invention of the lambda calculus in 1936 and have been a feature of programming languages since Lisp in 1958. Today, a growing number of modern programming languages support these functions.

Specifications of Lambda

lambda is an expression

lambda is not a statement, is an expression. Because of this, a lambda can appear in a place where def is not allowed. For example, places like inside a list literal, or a function call arguments. As an expression, lambda returns a value that can optionally be assigned a name. But, the def statement always assigns the new function to the name in the header, instead of returning it as a result.

A single expression

The lambda's body is similar to what we'd put in a def body's return statement. We simply type the result as an expression instead of explicitly returning it. Because it is limited to an expression, a lambda is less general that a def. You can only squeeze design, to limit program nesting. lambda is designed for coding simple functions, and def handles larger tasks.

Lambda functions

The lambda operator or lambda function is a way to create small anonymous functions, i.e. functions without a name. These functions are throw-away functions, i.e. they are just needed where they have been created. Lambda functions are mainly used in combination with the functions filter(), map() and reduce().

map function()

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. map() is a function with two arguments. The first argument func is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq. It returns a new list with the elements changed by func. map() can be applied to more than one list. The lists have to be the same length. map() will apply its lambda function to the elements of the argument lists.

Example -

list = [5,6,7,8,9]
squaredList = map(lambda x: x*x, list)
print(squaredList)

filter function()

The function filter(function, list) offers an elegant way to filter out all the elements of a list, for which the function function returns True. The function filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e. either True or False. This function will be applied to every element of the list l. Only if f returns True will the element of the list be included in the result list.

Example -

list = [1,2,3,4,5,6,7,8]
newList = filter(lambda x: x % 2 == 0, list)
print(newList)

reduce function()

The function reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value by combining elements via a supplied function.

Example -

list = [1,2,3,4]
s = reduce(lambda x,y: x+y,  list)
print(s)

Lambda function in Python

The lambda feature was added to Python due to the demand from Lisp programmers. In Python, anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.

The use of lambda Functions in Python

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.

Example -

# Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11]
new_list = list(map(lambda x: x * 2 , my_list))
# Output: [2, 10, 8, 12, 16, 22]

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.

Example -

# 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))
# Output: [4, 6, 8, 12]

With reduce()

The reduce is in the functools in Python. It is more complex. It accepts an iterator to process, but it's not an iterator itself. It returns a single result. At each step, reduce passes the current product or division, along with the next item from the list, to the passed-in lambda function. By default, the first item in the sequence initialized the starting value. This performs a repetitive operation over the pairs of the list. This is a part of functools module.

Example -

# Python code to illustrate
# reduce() with lambda()
# to get sum of a list
from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print (sum)
# Output: [193]

Where can be use Lambda functions?

The lambdas can be used as a function shorthand that allows us to embed a function within the code. For instance, callback handlers are frequently coded as inline lambda expressions embedded directly in a registration call's arguments list. Instead of being defined with a def elsewhere in a file and referenced by name, lambdas are also commonly used to code jump tables which are lists or dictionaries of actions to be performed on demand. This is mostly used in cases where one wishes or needs to implement some functionality within some framework or for the purpose of providing a call back ... and where the code involved will not be re-used by other parts of a program.  Often the code is dynamically generated. The graphical user interface (GUI) frameworks often require the programmer to associate (bind) functions to events, which are, in turn, associated with GUI elements (buttons, menus, windows, scrollbars, etc). Some of these functions are trivial (often simple expressions). It's common to pass lambdas into such GUI framework binding functions. You can think of this as a sort of "inline code" which obviates the need to define a normal (named) function in one suite of statements (lines) and refer to it from another place in the code.


Please write comments if you find anything different, or you want to share more information about the topic discussed above. Thank you!

Comments (0)

  • To add your comment please or

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.

Got It!