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

Gunjan Last Updated : 24 Oct, 2024
6 min read

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). This is a Complete Guide of Python Lambda Functions which will help you so 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()

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

What are Lambda Functions in Python?

In Python, an lambda/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))

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!

What is the syntax of a lambda function?

The syntax for a lambda function is generally the following:

lambda arguments: expression

Here’s a breakdown of the syntax:

  • lambda: This keyword signifies that you’re defining a lambda function.
  • arguments: This is a comma-separated list of arguments that the function can take. These arguments act like placeholders for the values that will be passed into the function when it’s called.
  • colon (:): This separates the arguments from the expression.
  • expression: This is the code that the function will execute. Unlike regular functions, lambda functions can only have one expression. This expression is evaluated and returned as the function’s output.

Here are some key points to remember about lambda functions:

  • Lambda functions are anonymous, meaning they don’t have a name.
  • They are typically used for short, concise functions that perform a simple task.
  • They are useful when you need to pass a function as an argument to another function (higher-order functions).

For instance, in Python, you can use a lambda function to double a number:

double = lambda x: x * 2

# Call the lambda function
result = double(5)
print(result)  # Output: 10

Difference Between Lambda functions and def defined function

Both def and lambda are used to define functions in Python, but there are some key differences between them:

Definition:

  • def: Used to define regular named functions. These functions can be multi-line and can contain complex logic including loops, conditional statements, and other function calls.
  • lambda: Used to define anonymous functions, also known as lambda functions. These functions are typically single-line expressions and are limited in their complexity.

Use Cases:

  • def: Suitable for defining functions that you plan to reuse throughout your code or functions that require complex logic.
  • lambda: Suitable for short, simple functions that are used only once or in a specific context, such as with built-in functions like map, filter, or reduce.

End Notes

Lambda functions in Python offer concise, anonymous function declarations ideal for one-liners and functional programming paradigms. They’re handy for quick operations, especially in filter(), map(), and reduce(). However, they might not suit complex logic or readability needs, where traditional def-defined functions are preferable for clarity and reusability. So at the End of this Article You have a complete understanding of python lambda Functions.

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.

Responses From Readers

Clear

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details