Learn everything about Analytics

Home » Anonymous or Lambda Functions in Python: A Beginner’s Guide!

Anonymous or Lambda Functions in Python: A Beginner’s Guide!

This article was published as a part of the Data Science Blogathon

Introduction

In this article, you’ll learn about the anonymous functions, which are also known as the Lambda functions. You’ll learn what they’re, their syntax, and the way to use them (with examples). The topics which we will be discussing in this article are as follows:

  • What are Anonymous or Lambda Functions in Python?
  • How to use Lambda Functions in Python?
  • Example of Lambda Functions in Python
  • Use of Lambda Functions in Python
  • Why use Lambda Functions?
  • When should you not use Lambda Functions?
  • Lambda Functions in map(), filter(), and reduce()

ME ANORMAL FUNCTION LAMBDA After Learning Lambdas | Lambda Meme on ME.ME| Lambda Functions in Python

                                      Image Source: Google Images

 

What are Anonymous Functions in Python?

In Python, an anonymous function may be a function that’s defined without a reputation.

While defining normal functions, we are using the def keyword in Python, but while defining anonymous functions we are using the lambda keyword.

Hence, anonymous functions also are called Lambda functions.

How to use Lambda Functions in Python?

A lambda function in python has the subsequent syntax.

Syntax of Lambda Function in Python:

lambda arguments: expression

Note that the Lambda functions can have any number of arguments but they have only one expression. Firtsly, the expression is evaluated and then returned. We used Lambda functions wherever function objects are required.

Example of Lambda Function in Python

In this section, we will see the example of a lambda function that doubles (i.e, multiply by two) the input value.

Program to indicate the utilization of Lambda functions:

double = lambda x: x * 2
print(double(10))

Output:

20

Code Explanation:

In the above code, lambda x: x * 2 is the lambda function. Also, their x is the argument and x * 2 is the expression that gets evaluated and returned to the user.

This function has no name. It returns a function object which is assigned to the identifier double. we will now call it a standard function. The statement

double = lambda x: x * 2

is nearly identical as:

def double(x):
return x * 2

Use of Lambda Functions in Python

We use lambda functions once we require a nameless function for a brief period of your time.

In Python, we generally use Lambda Functions as an argument to a higher-order function (a function that takes in other functions as arguments).

For Example, These are used together with built-in functions like filter(), map(), and reduce(), etc, which we will discuss later in this article.

Why use Lambda Functions?

As you may see in the previous section, lambdas are treated identically to regular functions at the interpreter level. In a way, you’ll say that lambdas provide compact syntax for writing functions that return one expression.

However, you must know when it’s a decent idea to use lambdas and when to avoid them. During this section, you may learn a number of the look principles utilized by python developers when writing lambdas.

One of the foremost common use cases for lambdas is in functional programming as Python supports a paradigm (or style) of programming referred to as functional programming.

It allows you to supply a function as a parameter to a different function (for example, in map, filter, etc.). In such cases, using lambdas offer a sublime thanks to creating a one-time function and pass it as the parameter.

 

When should you not use Lambda Functions?

In a production environment, You should never write complicated lambda functions, as it’ll be very difficult for coders who maintain your code to decrypt it. If you discover yourself making complex one-liner expressions, it might be a way superior practice to define a correct function.

Therefore, as a best practice, you wish to recollect that easy code is often better than complex code.

Lambda Functions in filter()

The filter function is employed to pick some particular elements from a sequence of elements. The sequence used in this function is an iterator such as lists, sets, tuples, etc.

The elements which can be selected are predicated on some pre-defined constraint. It takes 2 parameters:

  • A function that defines the filtering constraint.
  • A sequence (any iterator like lists, tuples, etc.)

For Example,

sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_answer = filter (lambda x: x > 6, sequences) 
print(list(filtered_answer))

Output:

[10, 8, 7, 11]

Code Explanation:

  • Within the first statement, we define a list container named as sequences that contain some numbers.
  • Here, we declare a variable called filtered_answer, which can store the filtered values returned by the filter() function.
  • A lambda function that runs on each element of the list and returns true if it’s greater than 6.
  • Print the result returned by the filter function.

 

Lambda Functions in map()

The map function is employed to use a specific operation for each element in a sequence. Like filter(), it also takes 2 parameters:

  • A function that defines how the operations to be performed on the elements.
  • One or more sequences.

For Example, 

In this example, we could make a program that prints the squares of numbers in an exceedingly given list:

sequences = [10,2,8,7,5,4,11]
squared_result = map (lambda x: x*x, sequences) 
print(list(squared_result))

Output:

[100, 4, 64, 49, 25, 16, 121]

Code Explanation:

  • Here, we define a list contained having name sequences that contain some numbers.
  • We declare a variable called squared_result which is able to store the mapped values.
  • A lambda function runs on each element of the list and returns the square of that number.
  • Print the result returned by the map function.

 

Lambda Functions in reduce()

The reduce function, like map(), is employed to use an operation to each element in a sequence. However, it’s working is a bit differs from the map function. The following steps are to be followed by the reduce() function to compute an output:

Step-1: Perform the defined operation on the primary 2 elements of the sequence.

Step-2: Save this result

Step-3: Perform the operation with the saved result and therefore the next element within the sequence.

Step-4: Repeat until no more elements are left.

It also takes two parameters:

  • A function that defines how the operations to be performed
  • A sequence (any iterator like lists, tuples, etc.)

For Example, 

In this example, we will make a program that returns the product of all elements present in a list given by the user.

from functools import reduce
sequences = [1,2,3,4,5,6]
product = reduce (lambda x, y: x*y, sequences)
print(product)

Output:

720

Code Explanation:

  • Import reduce from the functools module.
  • Here, we define a list container named sequences that contains some numbers.
  • We declare a variable called product which can store the reduced value.
  • A lambda function runs on each element step by step of the list and returns the product of that number as per the previous result.
  • Print the result returned by the reduce function.

This ends our discussion!

End Notes

I hope you enjoyed the article.

If you want to connect with me, please feel free to contact me on Email

Your suggestions and doubts are welcomed here in the comment section. Thank you for reading my article!

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

You can also read this article on our Mobile APP Get it on Google Play