How to create a lambda inside a Python loop?

PythonProgramming

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
raja
Published on 19-Apr-2018 17:46:57
Advertisements