The lambda function was initially introduced in the Python programming language because of the demand from LISP programmers. The term lambda originates from the Lambda Calculus, a form of mathematical calculus invented by Alonzo Church.
If the mention of Calculus has scared you, relax! You don’t have to master Calculus for using lambda functions. Lambda expressions are simple, concise and easy-to-understand – even a newbie can get the lambda syntax easily.
Lambda functions are one-liner functions. Every lambda function you define in python has three essentials – the keyword lambda, arguments and the expression. Here is the syntax of how we define a lambda function in python:
lambda arguments: expression
A lambda function is an anonymous function, i.e., a function without a name. It allows writing functions without naming them. Unlike the regular way of defining python functions, where we use the keyword def, we use the lambda keyword to define a lambda function.
# a function in python defined using the keyword – lambda lambda a, b: a + b
is similar to writing a regular function in python,
# a function in python defined using the keyword – def def sum(a, b): return a + b
sum = lambda a, b: a + b print("Result = ", sum(6,4))
Result = 10
Characteristics of Lambda functions in Python:
Attention: You can use lambda functions wherever there is a need for function objects. However, they cannot access variables other than those present in their parameter list. Also, global variables cannot be accessed using the lambda function.
A lambda function inside a lambda function is called a nested lambda function. Python allows lambda nesting, i.e., you can create another lambda function inside a pre-existing lambda function. For nesting lambdas, you will need to define two lambda functions – an outer and an inner lambda function. When the outer lambda is called, the inner lambda creates a function. The outer lambda then returns the called function.
Here is a small code to illustrate the nested lambda function:
Adding two numbers using Python lambda functions:
add = lambda a=20: lambda b: a + b x = add() print(x) print(x(30))
Here is a step-by-step explanation of the above code.
The assigned value of 30 is added up with the outer lambda function and finally, sum=50 is displayed in the output.
Nested lambda functions are significant when there is a need for function objects. Nesting allows hiding the mechanics of iteration operations, especially when working on complex projects. Nested lambdas can be easily embedded in places where def functions are restricted. Syntactically, they are useful in places where python wouldn’t allow a function to be defined using a regular def expression. Besides, nested lambda statements are also used along with sort methods to arrange the list elements in a sequence.
RuntimeError: maximum recursion depth exceeded error
In general, sort() in python has two parameters, key, and reverse. The key value is None, and the reverse value is False, by default. Using the lambda function in the sort method, the key extends its capabilities and becomes more versatile. Here is a simple code to make you understand the importance of the lambda function with the sort method.
Sorting without using lambda function:
check_list = [[4, "Cherry"], [3, "Banana"], [1, "Apple"], [2, "Dragon Fruit"]] check_list.sort() print(check_list)
[[1, 'Apple'], [2, 'Dragon Fruit'], [3, 'Banana'], [4, 'Cherry']]
Look at both the codes carefully. The inner list doesn’t get sorted using the regular sort() method but gets sorted using the lambda functions in alphabetical order. Therefore, the lambda function is of the utmost importance when there is a need to sort the inner list sequentially in a pre-defined list.
Lambda functions are also used with python in-built functions like filter(), map(), and reduce(). Let’s have a look at each in detail:
The filter () function in Python is an excellent way of filtering out all the elements of a sequence for which the function is True or False. The function includes only those values that satisfy the result and thus constructs a new list from those elements of the list for which the function returns True.
Here is a small code that returns the list of even numbers from an input list:
# Python code to illustrate filter() with lambda() # Finding the even numbers from a given list li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] result = list(filter(lambda x: (x%2 ==0), li)) print(result)
[2, 4, 6, 8, 10, 12, 14]
From the output of the above program, we see the output returning only the true values. Only those values in the range that are even numbers i.e., divisible by 2, are included in the new list, and the rest are explicitly removed.
The map() function in Python applies a unary function to each element in the list. After applying the specified function for each item in the list, the map() function returns the new list. The function calls each item in the sequence and returns a list of return values containing the results, in the same order.
Here is a small code that returns the list of cubes from an input list:
# Python code to illustrate map() with lambda() # Cubing the list of numbers from a given list nums= [1, 3, 5, 6, 4, 2] result = list(map(lambda x: x**3, nums)) print(result)
[1, 27, 125, 216, 64, 8]
From the output of the above program, we can see that all the elements have been evaluated for each of the elements in the list. The corresponding cubes of all the elements in the list are added to the new list sequentially.
The reduce() function combines the sequence elements using a binary function. It returns a single value generated by calling the function on the first two elements in the sequence. Once the two have been called, the result then gets added to the next item, and so on. The process continues until all the elements in the sequence get evaluated.
Pro-tip: Don’t forget to import reduce from the functools module.
Here is a small code that returns the list of the sum from an input list:
# Python code showing the use of reduce() with lambda() # Finding the sum from a given list lis = [1, 2, 3, 4, 5] result = reduce ((lambda a, b: a + b), lis) print(result)
The result of the first-two elements gets added to the next element. Here is what goes behind the scene à ((((1+2) + 3) + 4) + 5) = 15. The process is continued till the last element of the sequence is reached.
Lambda functions, no matter how simple they sound, also need to be tested at times. Testing a python lambda function is the same as testing a regular function. Unittest and doctest – python standard libraries are used to test lambda functions.
Lambda functions in python are an effective way to define functions anonymously. The lambda functions being executed and returned in a single-line add a significant advantage with throw-away functions. However, lambda functions are not recommended if the expressions become complicated to read or interpret. If it is strenuous to get all the logic inside lambdas, use a def instead.
Your email address will not be published. Required fields are marked *