Python - Function Lambda scope

Introduction

A lambda expression introduces a new local scope for the function it creates.

Lambdas can see all the variables that live in the functions where they are coded.

Demo

def func(): 
    x = 4 # ww w  . j  a v a2s  .c  om
    action = (lambda n: x ** n)          # x remembered from enclosing def 
    return action 

x = func() 
print(x(2))                              # Prints 16, 4 ** 2

Result

Related Topic