Hello python learners, hope all are well. Today we will learn about the python
lambda function. Keyword
lambda in python is used to create anonymous functions. Anonymous functions are those functions who are unnamed. That means you are defining a function without any name of the function.
Table of Contents
The following is a basic syntax of writing anonymous function using
Copylambda arguments: expression
Compare the above with function structure:
Copydef functionName( arguments ): statements... return something
Notice that, def is replaced by the keyword
lambda, then there is no function name, after that arguments are as usual arguments.
Function contains some statement then may return some value or not. But using
lambda, it will contain an expression that will be returned.
Python lambda function
Copydef squareof(x): return x*x p = squareof(5) print(p)
We can convert above function to python lambda function as follows:
Copyf = lambda x: x*x p = f(5) print(p)
Python lambda function will always return the output of the expression. The following is another example that takes two argument and return the greater one.
The output is:
Python lambda function is helpful for map or filtering of any list.
Python lambda function in filter()
If I want to filter from a list whether the values in the list are having length of 3. Notice that filter() is a function that takes two arguments. One is a function and the second one is a list of values. The following is the code for it:
Copyweekdays = ['sun', 'mon', 'tues', 'wed', 'thurs' 'fri'] days = filter(lambda day: day if len(day)==3 else '', weekdays) for d in days: print(d)
Output will be:
Copysun mon wed
In line 2, the function argument is an anonymous function, which takes arguments from the list of weekdays. And check whether the length of the value is equal to 3 or not. If 3 then return the value else nothing will be returned. And the output is according to what we wanted.
Use of python lambda function in map()
We can also use
lambda in map(). map is a function that takes two argument one is function, another is a list. The following code is an example which finds the remainder of all the number by 5.
Copynumbers = [ 74, 85, 14, 23, 56, 31,44 ] remainders = map(lambda num: num%5, numbers) for i in remainders: print(i)
The output will be:
Copy4 0 4 3 1 1 4
Thus you can create anonymous function using the python lambda keyword. For small functions,
lambda is helpful like shown above. Python lambda is similar to python list comprehension – both are a way to reduce the number of lines of code.
In many other function that takes function as input argument, you can use anonymous function using lambda keyword.
Hope now you will be able to play with the anonymous function and got understanding of lambda function in python. Thank you for reading this article.