Change language

Python Lambda (Anonymous Functions) | filter, map, reduce

| |

In Python, anonymous function means that the function has no name. As we already know, the def keyword is used to define normal functions, and the lambda keyword is used to create anonymous functions. It has the following syntax:

  lambda arguments: expression  
  • This function can have any number of arguments, but only one expression, which is evaluated and returned .
  • Anyone can use lambda functions wherever functional objects are required.
  • You should be aware that lambda functions are syntactically limited to a single expression.
  • It has various uses in certain areas of programming besides other types of function expressions.

Let’s take a look at this example and try to understand the difference between a regular defined def function and a lambda function . This is a program that returns a cube with a given value:

# Python code to illustrate the number cube
# shows the difference between def () and lambda ().

def cube (y):

return y * y * y; 

 

g = lambda x: x * x * x

print (g ( 7 ))

 

print (cube ( 5 ))

Output:

 343 125 
  • Without lambda: both are here returns a cube with a given number. But using def, we needed to define a function with a cube of names and pass a value to it. After execution, we also needed to return the result from where the function was called using the return keyword.
  • Using the lambda expression : the lambda definition does not contain a "return" statement, it always contains the expression that is returned. We can also put a lambda definition wherever a function is expected and we don’t need to assign it to a variable at all. This is the simplicity of lambda functions.

Lambda functions can be used in conjunction with built-in functions such as filter (), map (), and redu ().

Using lambda () with filter ()

The filter () function in Python takes a function and a list as arguments. This offers an elegant way to filter out all elements of the sequence for which the function returns True. Here is a small program that returns odd numbers from the input list:

# Python code for illustration
# filter () with lambda ()

li = [ 5 , 7 , 22 , 97 , 54 , 62 , 77 , 23 , 73 , 61 ]

final_list = list ( filter ( lambda x: (x % 2 ! = 0 ), li))

print (final_list)

Output:

 [5, 7, 97, 77, 23, 73, 61] 

Using lambda () with map ()

The map () function in Python takes a function and a list as an argument. The function is called with a lambda function and a list, and a new list is returned that contains all the lambda changed elements returned by this function for each element. Example:

# Python code for illustration
# map () with lambda ()
# to get a double list.

li = [ 5 , 7 , 22 , 97 , 54 , 62 , 77 , 23 , 73 , 61 ]

final_list = list ( map ( lambda x: x * 2 , li))

print (final_list)

Output:

 [10, 14, 44, 194, 108, 124, 154, 46, 146, 122] 

Using lambda () with the Reduce () method

The Reduce () function in Python takes a function and a list as an argument. The function is called with a lambda function and a list, and a new shorthand result is returned. This performs a repetitive operation on the pairs of the list. It is part of the functools module. Example:

# Python code for illustration
# reduce () with lambda ()
# to get the sum of the list

from functools import reduce

li = [ 5 , 8 , 10 , 20 , 50 , 100 ]

sum = reduce  (( lambda x, y: x + y), li)

print ( sum )

Output:

 193 

Here the results of the previous two elements are appended to the next element, and this continues to the end of the list, for example ((((5 + 8) +10) +20) +50) +100).

This article is provided by Chinma Lenka . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically