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 
#   w ww .j  av  a2  s  .c  o m
act = a() 
msg = act('robin')                            # 'robin' passed to x 
print( msg )
print( act )                                  # act: a function, not its result

Result

Related Topic