Have you ever faced the challenge of not being able to remember a function or variable name while coding? You must have had to scroll to the top of the code to find that name so you could use it. You may have even used the same name for two different variables, which must have caused a lot of confusion. These problems can occur quite often, especially in complex codes like the one shown above. Would it not be convenient if you could use a function only one time, execute a command with it, and then forget all about it? Fortunately, you can do just that by using the Python lambda (anonymous) function.
What are Lambda Functions in Python?
Python and other programming languages like Java, C++, and C# have small anonymous functions called lambda meant for one-time use. While we use the def keyword to define a function in Python, we use the lambda keyword to define an anonymous function. As the name suggests, the function that is defined using this keyword will have no name. Since we use the lambda keyword, we also call these functions as lambda functions.
How to use Lambda Functions in Python?
If you want to use the Python lambda (anonymous) function, you will have to follow this syntax:
lambda [arguments] : expression
The lambda function can have any number of arguments, or no arguments at all, after the colon (:). When you call the lambda function, you will see that the expression after the ‘:’ is executed. Let’s understand this through an example.
square = lambda a : a * a
In the above example, we want to execute a program to find the square of a number. We start the function by using the lambda keyword and follow it by giving it an argument ‘a’. The expression in the above code (a*a) will return the square value of a when we call the function.
We assign the entire lambda function to the variable ‘square’.
We get the output:
The variable name becomes the function name in this example, and we can use it as a regular variable.
Characteristics of the Lambda Function
- The function can take any number of arguments (numbers, letters, words, etc.) but can only have one expression.
- The function can be used anywhere in the code where functions are required.
- They are syntactically restricted to a single expression. That means, you cannot use loops or a conditional statement like for, while, if, else, etc., with a lambda function.
Use of Lambda Function in Python
# Python code for cube of a number # Using def keyword def cube(c): return c*c*c # Using lambda keyword l_cube = lambda c: c*c*c # using a normally defined function print(cube(6)) # using the lambda function print(lambda_cube(6))
Consider the code above. Can you see a difference in code for calculating the cube of a number? In the above code, we show the difference between defining and calling a normal function and a lambda function.
Both the cube() function and the l_cube() function perform the same calculations as we expected. So, what is the difference?
Both the functions return the cube of a number. However, we had to define a named function (cube) using the def keyword in the first code and then pass a value in it. We also had to use the return keyword to return the result from where we called the function.
On the other hand, when using the lambda function, we did not have to use the return keyword as it always contains an expression that is returned.
Hence, we use the lambda function or the anonymous function to simplify the code into one-line expressions. We also use them when we require a function for a short period of time. The simplicity of the function also allows us to use it anywhere it is expected, without having to assign a variable to it.
Using Built-in Functions like Filter() and Map() with Python Lambda (anonymous) Function
The Filter() Function
In Python, the filter() function takes in a function and a list as arguments. This gives us an easy way to filter all the elements in a sequence. When the lambda() function is passed in the filter() function (with the list to be evaluated) a new list is returned that contains items. Let’s consider the following example:
# Python code to use filter() with lambda() lis = [5, 7, 22, 9, 54, 6, 77, 2, 73, 66] final_li = list(filter(lambda x: (x%2 != 0) , li)) print(final_li)
In the code, a list of random numbers is assigned to the variable ‘lis’. We then call the filter() function and pass it as an argument in the lambda function. The function divides each number by 2 and returns “True” if the number is not equal to 0. We use the print function to print the new list.
The output will be:
[5, 7, 9, 77, 73]
The Map() Function
The map() function is similar to the filter() function as it takes in a function and a list. However, while the filter() function only prints values that are true, the map() function prints a new list that contains items returned by the function for each item. Let us look at an example:
# Python code to use map() with lambda() # to double each item in a list li = [5, 7, 25, 97, 82, 19, 45, 23, 73, 57] final_li = list(map(lambda x: x*2, li)) print(final_li)
In the above example, we have first created a list of random numbers called li. We then pass the map() function in the lambda() function. The expression in the lambda function multiplies every item in the list (doubles) and returns its value to final_li.
The output of the code will be:
[10, 14, 50, 194, 164, 38, 90, 46, 146, 114]
In conclusion, the Python lambda (anonymous) function is a no-name function declared in a single line. It can have only one expression and is used when a short-term function is required. It is defined using the lambda keyword and is similar to a regular function (defined by using the def keyword). We pass the lambda function as an argument in another function, as well.
Question and Answers
1. What is lambda in Python?
Answer: In Python, lambda is a keyword that is used to define a lambda function. You do not have to assign a name to these lambda functions, and you can use them anywhere in the Python code. The lambda expressions in Python find their root in lambda calculus, which is a complex computing language created by Alonzo Church in the 1930s.
2. Why is lambda used in Python?
Answer: Coding can sometimes be very confusing as we use a lot of variables and functions to execute tasks. The lambda function helps us reduce the code into one-line expressions. They work the same way as a normal function and give us the same results. However, they do not take up as much space and can be used for one-time executions.
3. How does lambda work in Python?
Answer: To use the lambda in Python, you will have to follow the following syntax:
lambda [arguments] : expression
The lambda keyword in the above syntax is used to define a lambda function. The function can take any number of arguments, which may be integers, strings, float, etc. However, there can only be one expression after the ‘:’. That means you cannot use a loop or conditional statements in the lambda function.
4. Try to write a lambda code that adds 12 to any number passed in the function as an argument. Also, use the lambda function to multiply one argument ‘a’ with another argument ‘b’.
# Adding 12 to a number num = lambda x : x + 12 print(num(15)) # Multiplying two numbers number = lambda a, b : a * b print(number(26, 7))
The output will be:
In the above code, we first use the lambda function to add 12 to any number that is given as an argument (in this example, the number is 15) and assign the name “num” to the function. When the function is called, the numbers are added and we get the output: 27.
In the next part of the code, we define two arguments (a and b) in the lambda function and write an expression to multiply them. We assign the name “number” to the function. When the function is called, the two numbers passed (26 and 7 in this example) are multiplied and we get the answer: 182