This article is focused on the specific use cases in which lambda functions are typically used in Python.
I remember the time when I first came across Lambda functions, though the syntax was easy to follow, what intrigued me was where in my code to actually employ these awesome guys, this article is all about learning when to wield the power of Lambda functions!
The table of contents below shows the various topics covered in this article, feel free to skip to the section of interest by clicking on it!
If you haven’t read our previous article on the fundamentals of Lambda functions, here it is!
Lambda Functions in Python: Explained Using 4 Examples!
If you are coming from the article above, here is a quick refresher just in case!
A Quick Refresher on Lambda Functions
Lambda functions are small anonymous functions. They are defined using the word lambda. They can take in any number of arguments but return only one value (evaluated from an expression).
An example lambda function that multiplies any given number by 2:
>> multiplyBy2 = lambda x: x*2
>> print(multiplyBy2(5))
10
Here the expression x*2 is evaluated, since the value of x is 5, 10(= 2×5) is returned.
The syntax of the lambda function is shown below:
variable_name = lambda argument: return evaluated_expression
Memorize this, you will save yourself from a lot of trouble later on!
The picture below shows another quick example of how we can squeeze so much code into a single line using lambda functions
Alright now that we have refreshed our memories, its time to move on to the topic of focus which is the uses of lambda functions!
Use Case#0: A function as an argument to another function
Lambda functions are commonly used when you have to use a function as an argument of another function. For instance:
A “callback function” can be said as the function that is passed to another function as an argument. Using lambda functions, the task becomes easy as you can just type the function then and there.
For example, see the following code using callback functions without using the lambda function:
def callbackfunc(num):
print("Callback called with num =", num)
def my_func(callback_func):
num = 1
callbackfunc(num)
my_func(callbackfunc)
And this is how it works using lambda functions:
def my_func(callback_func):
num = 2
callback_func(num)
my_func(lambda num: print("Callback called with num =", num))
As you can see, we just created and passed a whole function as an argument!
If this lambda syntax does not look too comfortable for you, I suggest giving our previous article on lambda function another read to get your fundamentals strong!
The reason I named this section as “Use Case#0” is because all the following use-cases uses this particular mechanism.
Let us have another example just to solidify the concept of “passing lambda functions as an argument“.
def apply_func(num, callback_func):
num2 = num + 5
return callback_func(num)
num = 5
result = apply_func(5, lambda x: x*10)
print(result)
To explain whats going on
- The function takes one argument (the value 5),
- adds 5 to it (value becomes 10)
- then passes it onto our lambda function
- the lambda function then multiplies it by 10 (value becomes 100) and
- the value gets printed out as shown below
OUTPUT
100
Alright now that we have a good grasp of the concept of “passing lambda functions as an argument“, let us see 3 specific use cases where this is especially useful!
Use Case#1: Filtering Data
Lambda functions are handy when it comes to filtering out elements from a list or any other collections based on a condition.
For example, let’s say I have a list containing 1 to 15 numbers and I need to filter out the even numbers from it, this is how it’s usually done:
num_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
def evensorter(num_list):
even_list = []
for number in num_list:
if number % 2 == 0:
even_list.append(number)
return even_list
print(evensorter(num_list))
OUTPUT:
[2, 4, 6, 8, 10, 12, 14]
And this is how we’ll do it with the Lambda function:
num_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
evensorter = lambda nums: (x for x in nums if x % 2 == 0)
print(list(evensorter(num_list)))
OUTPUT:
[2, 4, 6, 8, 10, 12, 14]
And just like that, we compressed the whole thing into just 3 lines of code!
Note: evensorted(num_list) just returns a lambda object, if you wanted to print what it contains you first have to convert it to list type
Use Case#2: Sorting Data
Lambda functions can be also used to sort data in a given collection of items.
For example, have a look at the following code where we sort a list of fruits based on the number of character that make up their names:
strings = ["apple", "banana", "mango", "fig", "watermelon"]
sorted_strings = sorted(strings, key=lambda x: len(x))
print(sorted_strings)
OUTPUT
['fig', 'apple', 'mango', 'banana', 'watermelon']
Use Case#3: Mapping Data
One other way the lambda function is highly useful is when we have to use the inbuilt map() function in Python.
In case you forgot what map() function does, The map() function
- takes in a list and a function as input,
- calls the function giving it one elements of the list at a time
- collects the results into another list
- returns the newly created list
Let’s say I have a list of names that are in lowercase, if I want them in uppercase this is how it usually will be done using normal functions:
names = ["tolkien", "martin", "hemingway"]
def uppercase(word):
return word.upper()
uppercase_names = map(uppercase, names)
print(list(uppercase_names))
OUTPUT
['TOLKIEN', 'MARTIN', 'HEMINGWAY']
The same can be achieved by easily using a lambda function as follows:
names = ["tolkien", "martin", "hemingway"]
uppercase_names = map(lambda name: name.upper(), names)
print(list(uppercase_names))
OUTPUT
['TOLKIEN', 'MARTIN', 'HEMINGWAY']
As you can see, we have achieved the exact same results using lambda functions, with much less code!
Summary
To summarize what we have seen so far, lambda functions are typically used as arguments with other built-in python functions such as sort(), filter() and map()
The example below shows a all 3 use cases!
num_list = [3, 1, 4, 2, 5, 8, 9, 10, 7, 6]
# Use Case#1: sort numbers using lambda function based on their squares
sorted_nums = sorted(num_list, key=lambda x: x**2)
print("Your sorted numbers are:", sorted_nums)
# Use Case#2: map numbers using lambda function by multiplying them by 2
mapped_nums = list(map(lambda x: x*2, num_list))
print("Your mapped numbers are:", mapped_nums)
#Use Case#3: filter numbers using lambda function by filtering numbers greater than 2
filtered_nums = list(filter(lambda x: x > 2, num_list))
print("Your filtered numbers are:", filtered_nums)
And with that example I will end this article!
Next time you come across these use-cases, make sure you wield the power of lambdas to make your code awesome!
Also, congratulations for making it till the end of the article, not many have the perseverance to do so!
I hope you enjoyed reading this article and found it useful!
Feel free to share it with your friends and colleagues!
If your thirst for knowledge have not been quenched yet, here are some related articles that might spark your interest!
Related Articles
Mutable and Immutable Data Types in python explain using examples
Python: Details contained in an Exception
Lambda Functions in Python: Explained Using 4 Examples!
Thanks to Namazi Jamal for his contributions in writing this article!