Learn About Python Lambda Functions and How to Use Them

Aayushi Johari
Edureka
Published in
7 min readJun 14, 2019

--

Python Lambda Functions — Edureka

A name is a convention that is used to refer to or address any entity. Almost everything around us has a name. The world of programming also goes in accordance to this. But is it a must to name everything? Or can you have something that is just ‘anonymous’? The answer is, yes. Python provides Lambda Functions, also known as Anonymous functions that are in fact nameless. So let’s move ahead to learn about these ‘Anonymous Mysteries’ of Python, in the following sequence.

  • Why are Python Lambda Functions required?
  • What are Python Lambda Functions?
  • How to write Lambda Functions?
  • How do Anonymous functions reduce the size of the code?
  • Python Lambda functions within user defined functions
  • How to use Anonymous functions within:
  1. filter()
  2. map()
  3. reduce()

So let’s begin :)

Why use Python Lambda Functions?

The main purpose of anonymous functions come into picture when you need some function just once. They can be created wherever they are needed. Due to this reason, Python Lambda Functions are also known as throw-away functions which are used along with other predefined functions such as filter(), map(), etc. These functions help reduce the number of lines of your code when compared to normal python functions.

To prove this, let’s move on further and learn about Python Lambda functions.

What are Python Lambda Functions?

Python Lambda functions are functions that do not have any name. They are also known as anonymous or nameless functions. The word ‘lambda’ is not a name, but its a keyword. This keyword specifies that the function that follows is anonymous.

Now that you are aware of what these anonymous functions refer to, let us move further to see how you write these Python Lambda functions.

How to write Lambda Functions in Python?

A Lambda function is created using the lambda operator and its syntax is as follows:

SYNTAX: lambda arguments: expression

Python lambda function can have any number of arguments but it takes just one expression. The inputs or arguments can start at 0 and go up to any limit. Just like any other functions, it’s perfectly fine to have lambda functions with no inputs. Therefore, you can have lambda functions in any of the following formats:

EXAMPLE:

lambda : “Specify the purpose”

Here, the lambda function is not taking any arguments.

EXAMPLE:

lambda a: “Specify the use of a

Here, lambda is taking one input which is a₁.

Similarly, you can have lambda a₁, a₂, a₃..aₙ.

Let’s take a few examples to demonstrate this:

EXAMPLE 1:

a = lambda x: x*x 
print(a(3)

OUTPUT: 9

EXAMPLE 2:

a = lambda x,y: x*y 
print(a(3,7))

OUTPUT: 21

As you can see, I have taken two examples here. The first example makes use of the lambda function with just one expression whereas the second example has two arguments passed to it. Please note that both functions have a single expression followed by the arguments. Therefore, lambda functions cannot be used where you need multi-line expressions.

On the other hand, normal python functions can take any number of statements in their function definitions.

How do Anonymous functions reduce the size of the code?

Before comparing the amount of code required, let’s first write down the syntax of normal functions and compare it with that of lambda functions described earlier.

Any normal function in Python is defined using a def keyword as follows:

SYNTAX:

def function_name(parameters):
statement(s)

As you can see, the amount of code required for a lambda function is quite less than that of normal functions.

Let us rewrite the example we took earlier using normal functions now.

EXAMPLE:

def my_func(x): 
return x*x
print(my_func(3))

OUTPUT: 9

As you can see, in the above example, we need a return statement within the my_func to evaluate the value of the square of 3. Contrarily, the lambda function does not make use of this return statement, but, the body of the anonymous function is written in the same line as the function itself, after the colon symbol. Therefore the size of the function is smaller than that of my_func.

However, lambda functions in the above examples, are called using some other variable a. This is done because these functions are nameless and therefore require some name to be called. But, this fact might seem confusing as to why use such nameless functions when you need to actually assign some other name to call them? And of course, after assigning the name a to my function, it doesn’t remain nameless anymore! Right?

It’s a legitimate question, but the point is, this is not the right way of using these anonymous functions.

Anonymous functions are best used within other higher-order functions that either make use of some function as an argument or, return a function as the output. To demonstrate this, let us now move on towards our next topic.

Python Lambda functions within user-defined functions:

Like mentioned above, lambda functions are used within other functions to mark the finest advantage.

The following example consists of new_func which is a normal python function that takes one argument x. This argument is then added to some unknown argument y which is supplied through the lambda function.

EXAMPLE:

def new_func(x):
return(lambda y: x+y)
t=new_func(3)
u=new_func(2)
print(t(3))
print(u(3))

OUTPUT:

6
5

As you can see, in the above example, the lambda function which is present within new_func is called whenever we make use of new_func(). Each time, we can pass separate values to the arguments.

Now that you have seen how to use anonymous functions within higher-order functions, let us now move ahead to understand one of its most popular use that is within the filter(), map() and reduce() methods.

How to use Anonymous functions within filter(), map() and reduce():

Anonymous functions within filter():

filter():

The filter() method is used to filter the given iterables(lists, sets, etc) with the help of another function, passed as an argument, to test all the elements to be true or false.

The syntax of this function is :

SYNTAX: filter(function, iterable)

Now consider the following example:

EXAMPLE:

my_list = [2,3,4,5,6,7,8]
new_list = list(filter(lambda a: (a/3 == 2), my_list))
print(new_list)

OUTPUT: [6]

Here, my_list is a list of iterable values which is passed to the filter function. This function uses the lambda function to check if there are any values in the list, that will equate to 2 when divided by 3. The output consists of a list that satisfies the expression present within the anonymous function.

map():

The map() function in Python is a function that applies a given function to all the iterables and returns a new list.

SYNTAX: map(function, iterable)

Let’s take an example to demonstrate the use of the lambda functions within the map() function:

EXAMPLE:

my_list = [2,3,4,5,6,7,8]
new_list = list(map(lambda a: (a/3 != 2), li))
print(new_list)

OUTPUT:

[True, True, True, True, False, True, True]

The above output shows that, whenever the value of the iterables is not equal to 2 when divided by 3, the result returned should be True. Hence, for all elements in my_list, it returns true except for the value 6 when the condition changes to False.

reduce():

The reduce() function is used to apply some other function to a list of elements that are passed as a parameter to it and finally returns a single value.

The syntax of this function is as follows:

SYNTAX: reduce(function, sequence)

EXAMPLE:

from functools import reduce 
reduce(lambda a,b: a+b, [23,21,45,98])

The above example is depicted in the following image:

OUTPUT: 187

The output clearly shows that all the elements of the list are added continually to return the final result.

With this, we come to the end this article on ‘Python Lambda’. Hope you are clear with all that has been shared with you. Make sure you practice as much as possible and revert your experience.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.

1. Python Tutorial

2. Python Programming Language

3. Python Functions

4. File Handling in Python

5. Python Numpy Tutorial

6. Scikit Learn Machine Learning

7. Python Pandas Tutorial

8. Matplotlib Tutorial

9. Tkinter Tutorial

10. Requests Tutorial

11. PyGame Tutorial

12. OpenCV Tutorial

13. Web Scraping With Python

14. PyCharm Tutorial

15. Machine Learning Tutorial

16. Linear Regression Algorithm from scratch in Python

17. Python for Data Science

18. Loops in Python

19. Python RegEx

20. Python Projects

21. Machine Learning Projects

22. Arrays in Python

23. Sets in Python

24. Multithreading in Python

25. Python Interview Questions

26. Java vs Python

27. How To Become A Python Developer?

28. How Netflix uses Python?

29. What is Socket Programming in Python

30. Python Database Connection

31. Golang vs Python

32. Python Seaborn Tutorial

33. Python Career Opportunities

Originally published at https://www.edureka.co on June 14, 2019.

--

--

Aayushi Johari
Edureka

A technology enthusiast who likes writing about different technologies including Python, Data Science, Java, etc. and spreading knowledge.