1

I would like to generate a family of lambda functions similar to this simplified example:

fns = [(lambda x: x == y) for y in range(10)]

The result I get from this is indeed a list of 10 functions. However, all 10 seem to have y bound to 9, which is the last value of the sequence. For example

[fns[i](9) for i in range(10)] --> [True, True, True, True, True, True, True, True, True, True]
fns[0](0) --> False

Why doesn't this work, and what's a clean work-around?

I've tried this in Python 2.7 and 3.3.

falsetru
  • 336,967
  • 57
  • 673
  • 597
Codie CodeMonkey
  • 7,339
  • 2
  • 27
  • 43

1 Answers1

1

Edited due to comment.

>>> fns = [(lambda x,y = y: x == y) for y in range(10)]
>>> map(lambda x: x(1), fns)
[False, True, False, False, False, False, False, False, False, False]
placeybordeaux
  • 2,008
  • 1
  • 17
  • 38