×

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined using the def keyword, but the lambda keyword is used for defining the Anonymous function.

Syntax of Lambda Function

lambda Arguments: expression

  • A lambda function can have any number of arguments.
  • A lambda function can have only one expression.
  • When function objects are required, a lambda function can be used.

Suppose you want to evaluate a function 3x+1 in python using function. One approach is declaring a standard function using the def keyword.

Let’s call it f that have a single parameter x. that will return value 3*x+1

def f(x):
    return 3 * x + 1
    # if we input 1, we will get the value 4.
print(f(1))

Output:

4

Let’s do this using anonymous function

g = lambda x: 3*x+1
print(g(1))

Output:

4

Examples

  1. lambda function with 0 argument:
show = lambda : “javatpoint”
print(show())

Output

javatpoint
  • lambda function with single argument:-
square = lambda x : x * x
print(square(5))

Output

25
  • lambda function with multiple arguments:-
multiply = lambda x, y: x * y
print(multiply(3,5))

Output

15

Need for Lambda Functions

Below are some points for why we need the lambda function, such as:

  • These functions are used when we need a function for a short time and namelessly, and only one expression is required.
  • Lambda functions are used when others need a function inside their body for a short time.
  • Lambda function can use where any function requires another function as a parameter.

Use of Lambda Function inside another Function

Let's say we need a function that returns a value true when a number is divisible by an unknown number so that the lambda function can be used.

# function to check if the number is divisible by a number n


def is_divisible(n):
return lambda a: a % n == 0


divisible_with_two = is_divisible(2)
print(divisible_with_two(15))


divisible_with_five = is_divisible(5)
print(divisible_with_five(15))

Output

False
True

Use of Lambda Function with Some Built-in Python Functions

  1. Use of lambda function with filter()

    The filter is a built-in function in python. It takes 2 parameters one is a function that returns a Boolean value, and another is iterable. It returns a new iterable, which contains the items that are evaluated true by the lambda function.
primary_list = [5, 6, 29, 34, 8, 21, 9] 	
# it is a primary list contains some items


new_list = list(filter(lambda x: x>10, primary_list))
# this list contain items of primary list which are grater than 10


print(new_list)

Output

[29, 34, 21]
  • Use of lambda function with map()

    The map is also a built-in function in python. It takes 2 parameters one is a function, and another is iterable. It returns a new iterable, which contains the items that are returned by the lambda function.
primary_list = [10, 45, 35, 70, 25, 40, 50]
# it is a primary list contains some items


new_list = list(map(lambda x: x // 5, primary_list))
# this list contains the items which we get after divide each item of pri-mary_list by 5
print(new_list)

Output

[2, 9, 7, 14, 5, 8, 10]
  • Use of lambda function with reduce()
    Reduce is also a built-in function in python. It takes 2 parameters one is a function, and another is iterable. It returns a result that we get after calling the lambda function for each pair. To use reduce function, we need to import functools.
from functools import reduce
primary_list = [3, 6, 8, 2, 9, 1]
# it is a primary list contains some items
multiplication = reduce(lambda x, y : x*y, primary_list)
print(multiplication)


Output

2592

Difference between Lambda Function and Normal Function

Here are some differences between lambda function and normal function, such as:

  • The Lambda function can only have a single expression, while a normal function can have multiple expressions in its body.
  • Normal functions are assigned a name, while the lambda function doesn’t have any name.
  • We need to write a return statement in the normal function to return a value, while no return statement is needed in the lambda function.

NOTE: Internal working of lambda function and normal function is same.


Related Topics

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

Python Redis Example

Introduction: Redis, representing Distant Word reference Server, is a kind of key-esteem NoSQL server. Redis is intended to help circle capacity for determination, holding information after power is stopped, and stores information...

5 minutes read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

AES CTR Python

Python Programming Language  Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Adding a key-value pair to dictionary in Python

Python dictionaries are collections of unsorted key-value pairs. This article will examine a method for adding new key-value teams to an existing dictionary. Dictionary in Python With the aid of curly brackets...

3 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary In Python, dictionaries are a useful and commonly used data structure in...

3 minutes read.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

Write a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

5 minutes read.

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

FOO in Python

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python Variables

Variables are one of the most important terms we should be familiar with if we want to be good programmers. In simpler words, we use variables to store a value....

4 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Continue and Pass Statements in Python

Difference between continue and pass statements in Python The tasks can be repeated and automated efficiently using loops in Python. Sometimes we have to exit from the entire loop completely, we...

2 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.

Python for Data Analysis

Data analysis uses various techniques to read, illustrate, manipulate and evaluate a particular data. You can have access to the data and keep the data updated regularly. You can append...

4 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.