×

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

Find Median of List in Python

The median is an enlightening measurement that is utilized as a proportion of the focal inclination of a circulation. It is equivalent to the centre worth of the conveyance. There...

3 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the...

3 minutes read.

Python float()

Python float() class The float() class in Python returns a floating point number constructed from a number or string x. Syntax class float([x]) Parameter x: This parameter represents a number or a string that can be converted...

1 minute read.

Python String join() method

Python String join() method The String.join() method in Python concatenates each element of an iterable (such as list, string and tuple) to the given string and returns the concatenated string. Syntax string.join(seq) Parameter Seq: This...

1 minute read.

Covariance in Python

Covariance is defined as the estimate of the difference of change between two variables or more variables. It defines the changes of two variables together. In Python, The covariance can...

2 minutes read.

Isodate 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 Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

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

Python exe() function

Python exe() function The exec() function in Python executes the specified Python code and accepts large blocks of code. It supports dynamic execution of Python code where the object must be either a string...

1 minute read.

Unit Testing in Python

The process of testing whether a particular unit is working properly or not is called “UNIT TESTING”. A unit test will check small components in your application. The first and...

7 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Python SymPy

A Python package for symbolic mathematics is called SymPy. Its goal is to develop into a fully-fledged computer algebra system (CAS) while maintaining the code as straightforward as possible to...

3 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Raise Exception in Python

Most of the programmers/developers create large programs to solve complex tasks in Python. The code can be of 1000 lines and even more based on the need of the problem....

5 minutes read.

Python String isalpha() method

Python String isalpha() method The string.isalpha () method in Python returns a boolean value true if all characters in the  string are alphabetic else for any other value it returns false. Syntax isalpha()  Parameter NA Return This...

1 minute read.