lambda function accessing outside variable [duplicate]

You can “capture” the i when creating the lambda

lambda x, i=i: x%i==0

This will set the i in the lambda’s context equal to whatever i was when it was created. you could also say lambda x, n=i: x%n==0 if you wanted. It’s not exactly capture, but it gets you what you need.


It’s an issue of lookup that’s analogous to the following with defined functions:

glob = "original"

def print_glob():
    print(glob) # prints "changed" when called below

def print_param(param=glob): # default set at function creation, not call
    print(param) # prints "original" when called below


glob = "changed"
print_glob()
print_param()

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)