- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is an anonymous function in Python?
An anonymous function in Python is one that has no name when it is defined. In Python, the lambda keyword is used to define anonymous functions rather than the def keyword, which is used for normal functions. As a result, lambda functions are another name for anonymous functions.
Syntax
Following is the syntax of the lambda function -
lambda [args] : expression
Although a lambda function can have only one expression, it can have any number of arguments. A lambda can also be immediately invoked and is written in a single line of code.
Example: Calling a lambda function
The lambda function begins with the keyword lambda and the parameter 'm' and 'n'. The value of the equation ‘½ *m * n’ after ':' is returned to the caller. To make it callable as a named function, the entire lambda function lambda ‘m,n : 1/2 * m * n’ is given to a variable ‘triangle’. As illustrated below, the variable name is converted into the function name so that it can be called like any other function.
# Finding the area of a triangle triangle = lambda m,n : 1/2 * m * n res=triangle(34,24) print("Area of the triangle: ",res)
Output
Following is an output of the above code -
Area of the triangle: 408.0
Alternate Solution
Following is an alternate way to define an anonymous function -
def triangle(m,n): return 1/2 * m * n print(triangle(4,6))
Output
Following is an output of the above code -
12.0
Note - It's not necessary for the expression to always return a value. The lambda function as shown in the following example returns nothing -
company = lambda name: print('EdTech', name) company('Tutorials Point')
Note − There can only be one expression in a lambda function. It is obvious that it cannot replace a function whose body contains loops, conditionals, etc.
Using lambda function with Python built-in functions
Using Python's built-in methods is a simple and effective approach to carry out operations with lambda functions. Due to the fact that these functions can accept lambdas as an argument and be called immediately, it is possible. When a nameless function is needed for a small duration, lambda functions are used.
Typically, we utilize it as an argument to a higher-order function in Python (a function that takes in other functions as arguments). Along with built-in functions like filter(), map(), and others, lambda functions are used.
Using the filter() function
Using the filter function, specific elements can be chosen from a list of elements. Any iterator, such as lists, sets, tuples, etc., can be used as the sequence. The elements that will be chosen will depend on a pre-defined constraint. There are two parameters -
A function that specifies the filtering constraint
A series of any iterator like lists, tuples, etc.
Example
In the example given below the use of the anonymous function ‘lambda’ in the filter() function is shown. In the first line, a list of numbers named ‘series’ is defined. Here, the filtered values produced by the filter() function are declared in a variable called 'result'. A lambda function that checks each item in the list and returns true if it is greater than ‘29’ is used. Then, print the outcome that the filter function returned -
series = [23,45,57,39,1,3,95,3,8,85] result = filter (lambda m: m > 29, series) print('All the numbers greater than 29 in the series are :',list(result))
Output
Following is an output of the above code -
All the numbers greater than 29 in the series are : [45, 57, 39, 95, 85]
Use in map() function
Every element in a series can have a specific operation performed to it using the map() function. Similar to filter() function, it requires two parameters i.e. a function that specifies the operation to be carried out on the elements and one or more sequences.
Example
Following is an example to show the use of the anonymous function ‘lambda’ in the map() function. Here, we define a list called series that has a number of items in it. We declare the 'result' variable, which will hold the mapped values. A lambda function that returns the cube of each number iteratively evaluated against in the list. The map function's outcome is then printed.
# printing the cube of numbers given in the list series = [23,5,1,7,45,9,38,65,3] result = map (lambda m: m*m*m, series) print('The cube of each element in the list are :',list(result))
Output
Following is an output of the above code -
The cube of each element in the list are : [12167, 125, 1, 343, 91125, 729, 54872, 274625, 27]
Use in reduce() function
Like the map() function, the reduce function is used to perform an operation on each element in a sequence. It operates differently from a map, though. The reduce() function performs the following steps before getting an output -
Apply the specified operation to the sequence's first two items.
Store this outcome.
Execute the operation using the previously saved result and the succeeding element of the sequence.
Continue until there are no more elements.
There are two additional parameters -
A method that specifies the action to be taken
A series of any iterator like lists, tuples, etc.
Note - The reduce() function is imported from the module named functools. This module provides higher-order functions such as reduce(), wraps(), cache() etc.
Example
In the following example, the use of the anonymous function ‘lambda’ in reduce() function is shown. From the functools module, import the reduce() function. Here, we define a list called 'series' that has a number of items in it. We declare a 'sum' variable that will hold the reduced value. A lambda function is given that iterates over each list item. It will then give you the result of the summation of that numbers.
# printing the sum of numbers given in the list from functools from functools import reduce series = [23,5,1,7,45,9,38,65,3] sum = reduce (lambda m,n: m+n, series) print('The total sum of all the elements in the list is :',sum)
Output
Following is an output of the above code -
The total sum of all the elements in the list is : 196