Lambda Functions in Python: Explained Using 4 Examples!

In this article, we’ll be learning about lambda functions with the help of 4 specifically chosen examples!

For those of you in a hurry, here is the short version of the answer!

Lambda Functions in a Nutshell

Lambda functions are small anonymous functions. They are defined using the word lambda.

Lambda functions can take in any number of arguments but return only one value (evaluated from the expression). 

An example of 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

Don’t worry if the above answer does not make sense to you as that was targeted at more experienced programmers who just wanted to refresh their memories. The rest of this article is dedicated to those of you in their first steps of their journey to become a Python Craftsman!

Lambda Functions Demystified

I remember the time when I first came across lambda functions, the whole syntax made me feel like I was reading ancient Latin, it was just overwhelming!

But along my Python journey as I kept seeing more and more of these new “syntax”es, one thing I understood is all these syntax are just “made up” by humans (the creators of the programming language) to serve a specific use-case.

All we need to do to wield their power is to memorize them and learn when exactly to use them in our programs.

Syntax are like magic spells, they might not make sense right away, but in time they will. Also they are quite powerful and come in very handy in situations!

embeddedinventor.com

In this article our goal is to learn the lambda syntax and see which situations to wield them in with the help of 4 carefully chosen examples!

Alright, lets begin!

Example#1 – Squaring a number:

Squaring a number is one of the easiest functions we can start with (and it becomes easier using a lambda function!).

First let’s see how to square a number through the usual way with a regular function:

def square_number(num):
    num = num ** 2
    return num

print(square_number(5))

OUTPUT

25

Pretty simple right? We have defined a function square_number that takes in an input num, squares it and returns it. We then call the function with value 5 and then print the returned value, which is 25 like you saw.

Using lambda function, the whole function creating procedure can be finished in just one line:

square_number = lambda num: num **2

print(square_number(5))

OUTPUT

25

Do you see now why lambda’s are so useful?

You might think all we did was shave off 2 lines of code with a complicated syntax. But, given the right situations, lambda functions become the most optimum choice.

For instance I could make the above code more compact by just compressing it all in one line:

print((lambda num: num **2)(5))

You did not have to waste time on writing a whole new function, if your function is simple enough you can get away with a one-liner, and that’s the power of lambda functions!

Lets see another simple example, this time with strings!

Example#2 – Getting the last letter from a word

In this example, our goal is to take a word from the user as input and return the last letter from that word as output.

The regular function version:

def last_letter(word):
    letter = word[-1]
    return letter
    
word = input("Please enter a word: ")
print("The last letter from your word is", last_letter(word))

OUTPUT

Please enter a word: qwerty
The last letter from your word is y

The lambda function version:

last_letter = lambda word: word[-1]

word = input("Please enter a word: ")
print("The last letter from your word is", last_letter(word))

OUTPUT

Please enter a word: hello
The last letter from your word is o

And that’s it! We have beautifully transformed a regular function into a lambda function again!

If you are interested in the “one-line version” here it is!

print("The last letter from your word is", (lambda word: word[-1])(input("Please enter a word: ")))

OUTPUT

Please enter a word: tree   
The last letter from your word is e

Okay what we have seen till now is pretty simple, I think its time to move on to the next level of complexity, lets do that with the third example!

Example#3 – Concatenating 2 strings

This time lets take 2 strings and join them together into one!

First, the regular function as usual

The regular function version

string1 = "or"
string2 = "ange"

def concatenate(string1, string2):
    result  = string1 + string2
    return result
    
my_word = concatenate(string1, string2)
print(my_word)

OUTPUT

orange

We’ll try the same thing with the lambda function now:
The lambda function version:

string1 = "or"
string2 = "ange"

concatenate = lambda string1, string2: string1 + string2
    
my_word = concatenate(string1, string2)
print(my_word)

OUTPUT

Orange

I am sure you are probably thinking, this example is still too simple! So

A Challenge For You!

Time for some active learning, which is the best way to learn coding, so here is a challenge, I hope you are up to it!

Notice we are taking in multiple inputs this time. Lambda functions allow any number of inputs, so here’s a challenge for you:

Create a lambda function that takes in 4 strings and returns the final concatenated string.

Take some time, refer to the previous example for syntax, try to get it running using lambdas!

I hope you managed to complete the challenge, and congratulations on doing so! You have almost mastered this concept of lambda functions!

Time to move on to the next level of complexity and learn one important thing about Lambda functions!

Example#4 – Getting the middle element from a list

This time we’re going to make a function that returns the middle element of a list.

Elements of a list are always indexed. This means to access a specific element you have in mind, you can simply specify their index number and Python will return that for you. You must also keep in mind that indexing in lists starts from 0, not 1! 

For example, for the list [“mango”, 21, [12,31,”hi”], “watermelon”], the indexes will be from 0 to 4 for each of the elements respectively.

For a visual understanding:

Moving on, in order to get the middle element, one can get it if they have their index. To get the index number, you only need to half the total length of the list and then round it off using the int() function. Let’s see how:

def middle_element(input_list):
    middle_index = int(len(input_list) / 2)
    return input_list[middle_index]

avengers = ["Iron Man", "Captain America", "Hulk", "Thor", "Black Widow", "Hawkeye", "Nick Fury"]
print(middle_element(avengers))

OUTPUT

Thor

We get the output ‘Thor’ since it is the middle element in our list

To do the same thing using lambda functions:

middle_element = lambda input_list: input_list[int(len(input_list) / 2)]

avengers = ["Iron Man", "Captain America", "Hulk", "Thor", "Black Widow", "Hawkeye", "Nick Fury"]
print(middle_element(avengers))

OUTPUT

Thor

You would have noticed that this is comparatively complex and hard to read at the first sight, and you’re absolutely right!

If you think otherwise, then think of your teammates/ other people who might have to read your code! They might not be as brilliant as you, or their thought processes might be different as compared to yours!

The term used to refer to this is called “code readability“, which is a qualitative measure of the ease of reading the code.

I think we can all agree that this one-liner scores terribly in “code readability”!

That is why you have to be careful when writing your code, less code readability will cause a bunch of problems in the future, just trust me on this one!

For example I often had trouble understanding my own code a week after writing it, so I usually just end up deleting the shitty code and starting all over, which means the first time was a total waste of time!

The same goes for a different reader, let’s say someone else in your development team reads the code, they will have a difficult time understanding what you wrote.

So always this keep in mind while using lambda functions

Code readability always comes first!

Some more challenges to help solidify the concept

To end with, try to complete the following short tasks, by the end you would have understood pretty much everything you need to understand about lambda functions:

Tasks: Write lambda functions for each of the following:

  1. Add two numbers
  2. Get the product of four given numbers
  3. Get the length of a tuple
  4. Get the first letter of a given string

Once again, remember that cramping a lot of functions into one-lines is not always the best idea!

Now you know “how” to use lambda functions, but in the intro I promised to talk about “when” is the right time to wield its power which we have not seen yet. Don’t worry I did not forget about that, I decided to focus on that topic in an article of its own which you can find in the link below!

Lambda Functions In Python: Uses Explained!

Lambda functions actually have different use cases, from pairing with inbuilt functions like sort(), filter(), map() to being used as callback functions. If you want to see how it’s done, I’ve explained it in the above article.

And with that I will end this article.

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

Python lists: Append vs Extend

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn