Python - Lambda using local variable

Introduction

Lambda expressions introduce a local scope.

It can use names in enclosing functions, the module, and the built-in scope:

Demo

def a(): 
    title = 'Sir' 
    action = (lambda x: title + ' ' + x)      # Title in enclosing def scope 
    return action                             # Return a function object 
# from  w w  w .j a  v  a 2 s  .co  m
act = a() 
msg = act('robin')                            # 'robin' passed to x 
print( msg )
print( act )                                  # act: a function, not its result

Result

Related Topic