Python - Using a list of lambda

Introduction

Create a list of lambda:

Demo

L = [lambda x: x ** 2,               # Inline function definition 
     lambda x: x ** 3, 
     lambda x: x ** 4]               # A list of three callable functions 
# from   www. ja  v a 2  s  . c  o m
for f in L: 
    print(f(2))                      # Prints 4, 8, 16 

print(L[0](3))                       # Prints 9

Result

Which is the same as follows:

Demo

def f1(x): return x ** 2 
def f2(x): return x ** 3             # Define named functions 
def f3(x): return x ** 4 

L = [f1, f2, f3]                     # Reference by name 
# w w w  .j  a v  a  2 s  .co m
for f in L: 
    print(f(2))                      # Prints 4, 8, 16 

print(L[0](3))                       # Prints 9

Result

Related Topic