
Today we will learn about the lambda function in Python and explore its advantages and limitations.
Let’s do it!
What is a Lambda Function in Python
A lambda function is an anonymous function (i.e., it has no name defined) that can take any number of arguments, but unlike a normal function, it only computes and returns a single expression.
The syntax for a lambda function in Python is as follows:
lambda parameters: expression
A lambda function consists of three elements:
- The keyword lambda: similar to def in a normal function
- Parameters: supports passing positional and keyword arguments, just like normal functions
- The body: the expression that processes the given parameters
It is important to note that, unlike normal functions, there is no need to enclose the parameters of a lambda function in parentheses. If the lambda function has two or more parameters, we list them separated by commas.
We use lambda functions to compute a single short expression (ideally a single line) and it is computed only once, meaning we won’t reuse this function later. Generally, we pass lambda functions as arguments to higher-order functions (functions that take other functions as arguments), such as Python built-in functions like filter(), map(), or reduce().
How Lambda Functions Work in Python
Let’s look at a simple example of a lambda function:
lambda x: x + 1
Output:
<function __main__.<lambda>(x)>
The above lambda function takes one argument, increments it by 1, and returns the result.
It is a simpler version of the following normal function that uses def and return keywords:
def increment_by_one(x):
return x + 1
So far, our lambda function lambda x: x + 1 only creates a function object and does not return anything because we haven’t provided any value for its parameter x. Let’s assign a variable and pass it to the lambda function to see what we get this time:
a = 2
print(lambda x: a + 1)
Output:
<function <lambda> at 0x00000250CB0A5820>
Our lambda function did not return 3 as we expected, but instead returned the function object itself and its memory location, indicating that this is not the correct way to call the lambda function. To pass parameters to the lambda function, execute it and return the result, we should use the following syntax:
(lambda x: x + 1)(2)
Output:
3
Although the parameters of our lambda function are not enclosed in parentheses, when we call it, we add parentheses around the entire lambda function construct along with the parameters we pass to it.
Another thing to note in the above code is that using a lambda function allows us to immediately invoke the function after creating it and receive the result. This is known as Immediately Invoked Function Expression (IIFE).
We can create a lambda function with multiple parameters, in which case we separate the parameters in the function definition with commas. When we execute such a lambda function, we list the corresponding parameters in the same order and separate them with commas:
(lambda x, y, z: x + y + z)(3, 8, 1)
Output:
12
We can also use lambda functions to perform conditional operations. Below is a simple if-else simulation using lambda:
print((lambda x: x if(x > 10) else 10)(5))
print((lambda x: x if(x > 10) else 10)(12))
Output:
10
12
If there are multiple conditions (if-elif-…-else), we must nest them:
(lambda x: x * 10 if x > 10 else (x * 5 if x < 5 else x))(11)
Output:
110
However, the above syntax makes the code harder to read.
In such cases, a normal function with if-elif-…-else conditions would be a better choice than a lambda function. In fact, we could write the lambda function in the above example as follows:
def check_conditions(x):
if x > 10:
return x * 10
elif x < 5:
return x * 5
else:
return x
check_conditions(11)
Output:
110
Although the above function adds more lines than the corresponding lambda function, it is easier to read.
We can assign a lambda function to a variable and then call that variable as a normal function:
increment = lambda x: x + 1
increment(2)
Output:
3
However, according to Python’s PEP 8 style guidelines, this is considered bad practice.
The use of assignment statements eliminates the only advantage lambda expressions have over explicit def statements (i.e., that they can be embedded in larger expressions).
Therefore, if we do need to store a function for further use, it is better to define an equivalent normal function instead of assigning a lambda function to a variable.
Applications of Lambda Functions in Python
Lambda with filter() Function
The filter() function in Python requires two parameters:
- A function that defines the filtering criteria
- An iterable object on which the function operates
When we run the function, we get a filter object:
lst = [33, 3, 22, 2, 11, 1]
filter(lambda x: x > 10, lst)
Output:
<filter at 0x250cb090520>
To obtain a new iterator from the filter object, and all items in the original iterator meet the predefined conditions, we need to pass the filter object to the corresponding Python standard library functions: list(), tuple(), set(), frozenset(), or sorted() (which returns a sorted list).
Let’s filter a list of numbers, selecting only those greater than 10 and returning a sorted list in ascending order:
lst = [33, 3, 22, 2, 11, 1]
sorted(filter(lambda x: x > 10, lst))
Output:
[11, 22, 33]
We do not have to create a new iterable object of the same type as the original object; additionally, we can store the result of this operation in a variable:
lst = [33, 3, 22, 2, 11, 1]
tpl = tuple(filter(lambda x: x > 10, lst))
tpl
Output:
(33, 22, 11)
Lambda with map() Function
We use the map() function in Python to perform a specific operation on each item in an iterable. Its syntax is similar to filter(): a function to execute and an iterable object that the function applies to.
The map() function returns a map object, and we can obtain a new iteration from it by passing that object to the corresponding Python functions: list(), tuple(), set(), frozenset(), or sorted().
Like the filter() function, we can extract an iterable object of a different type from the map object and assign it to a variable.
Here is an example using the map() function to multiply each item in the list by 10 and output the mapped values as a tuple assigned to the variable tpl:
lst = [1, 2, 3, 4, 5]
print(map(lambda x: x * 10, lst))
tpl = tuple(map(lambda x: x * 10, lst))
tpl
Output:
<map object at 0x00000250CB0D5F40>
(10, 20, 30, 40, 50)
An important difference between map() and filter() is that the first function always returns an iterable of the same length as the original function. Therefore, since pandas Series objects are also iterable, we can apply the map() function on DataFrame columns to create a new column:
import pandas as pd
df = pd.DataFrame({'col1': [1, 2, 3, 4, 5], 'col2': [0, 0, 0, 0, 0]})
print(df)
df['col3'] = df['col1'].map(lambda x: x * 10)
df
Output:
col1 col2
0 1 0
1 2 0
2 3 0
3 4 0
4 5 0
col1 col2 col3
0 1 0 10
1 2 0 20
2 3 0 30
3 4 0 40
4 5 0 50
Of course, to obtain the same results in the above case, we could also use the apply() function:
df['col3'] = df['col1'].apply(lambda x: x * 10)
df
Output:
col1 col2 col3
0 1 0 10
1 2 0 20
2 3 0 30
3 4 0 40
4 5 0 50
We can also create a new DataFrame column based on certain conditions, for the code below, we can interchangeably use map() or apply() functions:
df['col4'] = df['col3'].map(lambda x: 30 if x < 30 else x)
df
Output:
col1 col2 col3 col4
0 1 0 10 30
1 2 0 20 30
2 3 0 30 30
3 4 0 40 40
4 5 0 50 50
Lambda with reduce() Function
The reduce() function is related to the functools Python module, and it operates as follows:
- Operates on the first two items of an iterable and saves the result
- Operates on the saved result and the next item in the iterable
- Continues in this manner until all items in the iterable are used
This function has the same two parameters as the previous two functions: a function and an iterable object. However, unlike the previous functions, this function does not need to be passed to any other function; it directly returns a scalar value:
from functools import reduce
lst = [1, 2, 3, 4, 5]
reduce(lambda x, y: x + y, lst)
Output:
15
The above code demonstrates how we use the reduce() function to calculate the sum of a list.
It is important to note that the reduce() function always requires a lambda function with two parameters, and we must first import it from the functools Python module.
Advantages and Disadvantages of Lambda Functions in Python
Advantages
- It is ideal for evaluating a single expression that should only be evaluated once.
- It can be invoked immediately after definition.
- Its syntax is more compact compared to the corresponding normal syntax.
- It can be passed as an argument to higher-order functions like filter(), map(), and reduce().
Disadvantages
- It cannot perform multiple expressions.
- It can easily become cumbersome and less readable, especially when it includes an if-elif-…-else loop.
- It cannot contain any variable assignments (e.g.,
lambda x: x=0will raise a syntax error). - We cannot provide a documentation string for a lambda function.
Conclusion
In summary, we have discussed in detail many aspects of defining and using lambda functions in Python:
- How lambda functions differ from normal Python functions
- The syntax and analysis of lambda functions in Python
- When to use lambda functions
- How lambda functions work
- How to call lambda functions
- The definition of Immediately Invoked Function Expression (IIFE)
- How to use lambda functions to perform conditional operations, how to nest multiple conditions, and why we should avoid it
- Why we should avoid assigning lambda functions to variables
- How to use lambda functions with the filter() function
- How to use lambda functions with the map() function
- How we use lambda functions in pandas DataFrame
- Lambda functions with the map() function – and alternative functions used in those cases
- How to use lambda functions with the reduce() function
- The advantages and disadvantages of using lambda functions in normal Python
We hope that today’s discussion makes the seemingly daunting concept of lambda functions in Python clearer and easier to apply. If you liked it, please give us a thumbs up!
Recommended Reading:
Getting Started: The Most Comprehensive Zero-Basis Python Learning Questions | Zero-Basis Python Learning After 8 Months | Practical Projects | Learning Python is This Shortcut
Useful: Scraping Douban Short Reviews, Movie "Us" | Analysis of the Best NBA Players in 38 Years | From High Expectations to Disappointment! Detective Chinatown 3 is Disappointing | Laughing at the New Legend of the Dragon Slayer | Riddle Answering King | Using Python to Make Massive Sketches of Beautiful Girls | Detective Chinatown is So Hot, I Used Machine Learning to Make a Mini Recommendation System for Movies
Fun: Pinball Game | 9-Puzzle | Beautiful Flowers | 200 Lines of Python "Cool Running" Game!
AI: A Robot That Can Write Poetry | Coloring Pictures | Predicting Income | Detective Chinatown is So Hot, I Used Machine Learning to Make a Mini Recommendation System for Movies
Tools: Pdf to Word, Easily Handle Tables and Watermarks! | Save HTML Web Pages as PDF with One Click! | Goodbye PDF Extraction Fees! | Create the Ultimate PDF Converter with 90 Lines of Code, Converting Word, PPT, Excel, Markdown, HTML with One Click | Create a DingTalk Low-Cost Flight Reminder! | 60 Lines of Code to Make a Voice Wallpaper Switcher to Watch Beautiful Girls Every Day! |
Annual Blockbuster Copywriting
1). Wow! Pdf to Word Easily Done with Python!
2). Learning Python is Really Great! I Made a Website with 100 Lines of Code, Helping People Photoshop Travel Pictures, Earning a Little Chicken Leg to Eat.
3). Over a Billion Views on Premiere, Exploding All Over the Internet, I Analyzed "Sisters Who Make Waves" and Discovered These Secrets.
4). 80 Lines of Code! Used Python to Make a Doraemon Clone.
5). 20 Python Codes You Must Master, Short and Powerful, Invaluable.
6). 30 Python Tricks Collection.
7). The 80-Page "Beginner's Selection of Python Essentials.pdf" I Summarized, All Valuable Content.
8). Goodbye Python! I'm Going to Learn Go! In-Depth Analysis of 2500 Words!
9). Found a Benefit for a Dog Licker! This Python Scraping Tool is So Cool, Automatically Downloading Girl Images.
Click to Read the Original Text, Watch My Video on Bilibili!