How to create a lambda inside a Python loop?


You can create a list of lambdas in a python loop using the following syntax −

Syntax

def square(x): return lambda : x*x
listOfLambdas = [square(i) for i in [1,2,3,4,5]]
for f in listOfLambdas: print f()

Output

This will give the output −

1
4
9
16
25

You can also achieve this using a functional programming construct called currying. 

example

listOfLambdas = [lambda i=i: i*i for i in range(1, 6)]
for f in listOfLambdas:
   print f()

Output

This will give the output −

1
4
9
16
25

Lakshmi Srinivas
Lakshmi Srinivas

Programmer / Analyst / Technician

Updated on: 05-Mar-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements