×

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

Python format() function

Python format() function The format() function in Python formats a specified value into the given format. A ‘TypeErrorexception’ is raised if the method search reaches the object and the format_spec is non-empty, or if either the format_spec or the...

1 minute read.

Python BS4 Code

Python BS4 Code The BS4 stands for BeautifulSoup version 4.x. The BeautifulSoup is a Python library which is used for pulling out data of the HTML & XML files using the...

14 minutes read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.

Python List extend() method

Python List extend() method The list.extend() method extends the list by appending all the items from the iterable. Syntax list.extend(iterable) Parameter iterable: It is a required parameter which represents any iterable unlike list, set, tuple, etc. Example 1 # Python...

1 minute read.

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute read.

Flutter Python

The flutter is a frame work available in the python programming language, to create web applications, mobile apps. The flutter is generally used for the development of the backend of...

3 minutes read.

Python program to perform the arithmetic operation

Python program to perform the arithmetic operation This program will write a code to perform some basic arithmetic operations like addition, subtraction, multiplication, exponent, modulus, and division. Here we first need...

2 minutes read.

Gaussian elimination in python

Linear and polynomial equations are used in almost all fields of numerical simulation. However, its most common use in engineering is in the area of linear system analysis. The broader...

3 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

How to Install Pandas in Python?

Pandas is a library created in Python for handling and analyzing data. Pandas provides a variety of procedures and data structures for manipulating time series and numerical data.  Pandas is...

3 minutes read.

Python | Read csv using pandas.read_csv()

Python is an excellent language for performing information analysis, owing to the fantastic biological system of information-driven python packages. Pandas is one of those packages that make taking in and...

4 minutes read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Fsolve 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.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

Is Python Case-sensitive when Dealing with Identifiers

Yes, Python is a case-sensitive language while dealing with identifiers. Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. It is a case-sensitive...

6 minutes read.

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

Standard Scaler in SKLearn

The sci kit learns in python is a library thatch is used in machine learning which is used to work on data modeling.It is only focused on the data modeling,...

4 minutes read.