How external variables can be passed into the scope of lambda functions?

Viewed 177

I want to define a lambda function inside another lambda function, but when I create the inner lambda function, the outer lambda function's argument is said to be undefined, like this.

# time, game, players... are defined above this line
result = filter(lambda x: (player == min(players, key=lambda y: time(game, y, x))), words)

Then, the x as one of the time function's argument is said to be an undefined variable. I searched through StackOverflow and found that I can use a default value to pass x into the scope of lambda y by changing it to lambda y, x=x: time(game, y, x).

I am wondering why x couldn't be used in the scope of lambda y directly, just like how game, time() are used in it. Aren't game, time, x all variables outside the scope of lambda y? What's the difference between x and these other variables/functions.

Thanks very much! The error information

1 Answers

I am not sure why you are having the problem. In a minimal example like this:

(lambda x: (lambda y: y+x)(3))(2)

You get the expected 5, so there must be something more to what you are doing.

Related