×

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 TCP Server

The TCP server library is also known as the socket library. Socket programming is the method of connecting two nodes through a network to form communication between two nodes. In...

3 minutes read.

How to handle exceptions in python

Prerequisite: Exceptions and errors in Python What are Exceptions? Exceptions are run-time errors that unexpectedly occur and crash a program. When occurred, it alters the flow of the program. These errors are...

9 minutes read.

Python Bubble Sort

Bubble sort is one of the techniques used to sort the elements in lists in a certain order, either in ascending or descending order. It is called Bubble sort because...

4 minutes read.

Python program to check whether a given number is prime or not

Python program to check whether a given number is prime or not A positive integer greater than 1 is called a prime number if it is divisible by one and number...

1 minute read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Python Lexicographic Order

Python lexicographic order Before we discuss the lexicographic order in Python, we should understandwhat is lexicographic order and sort according to lexicographic order. Lexicographic order In mathematics, the generalization of the alphabetical order...

5 minutes 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.

Python program to check if two strings are anagram or not

Python program to check if two strings are anagram or not Problem: This is a python program that takes two strings and checks if given strings are anagram or not. Examples: Input: string1...

1 minute read.

How to Configure Python Interpreter in Eclipse

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.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

Python Online Compiler

Compose, Run and Offer Python code internet involving OneCompiler's Python online compiler free of charge. It's one of the hearty, highlight-rich web-based compilers for python language, supporting both the adaptations, which...

3 minutes read.

Python Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

Removing the First Character from the String in Python

String The string is the collection of characters. The strings in python are “immutable”; we cannot change a string once they are created. In python, whatever data we take as input...

4 minutes read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 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 NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.