Python Lambda

Python Lambda

Python lambda:

  • an expression form that generates function objects.
  • anonymous (i.e., unnamed) function

lambda is designed for coding simple functions

def handles larger tasks

'''lambda Basics'''

# ------- lambda expression ------- #
f = lambda x, y, z: x + y + z                   # returns a function that can optionally be assigned a name

# ------- def statements ------- #
def func(x, y, z):                              # always assigns the new function to the name automatically
    return x + y + z
    
print(func(2, 3, 4) == f(2, 3, 4))


'''Why Use lambda?'''

# ------- lambda expression ------- #
# provide code proximity: if only be used in a single context and not used anywhere else
# stuff small pieces of executable code into places where statements are illegal syntactically
L1 = [lambda x: x ** 2,                         # inline function definition
    lambda x: x ** 3,
    lambda x: x ** 4]                           # a list of three callable functions

for f in L1:
    print(f(2))                                 # prints 4, 8, 16
print(L1[0](3))                                 # prints 9

# ------- def statements ------- #
def func1(x): return x ** 2                     # define named functions
def func2(x): return x ** 3                     # function definitions outside the context of intended use (which might be hundreds of lines away)
def func3(x): return x ** 4
L2 = [func1, func2, func3]                      # reference by name
for f in L2:
    print(f(2))                                 # prints 4, 8, 16
print(L2[0](3))                                 # prints 9

相关推荐