fl <rxjw...@gmail.com> writes: > Hi, > > I cannot reason out why the code: > //////// > def mpl(): > return [lambda x : i * x for i in range(4)] > > print [m(2) for m in mpl()] > ///////// > > has result: > > [6, 6, 6, 6]
The "i" in your lambda definition is a variable reference which is not dereferenced (i.e. name replaced by the value) at definition but only at call time. Thus, all your "lambda"s are in fact equal; they all look up the current value of "i" when they are called (which happens to be "3"). To avoid this, you must force the dereferencing at definition time. This could look like: return [lambda x, i=i: i * x for i in range(4)] -- https://mail.python.org/mailman/listinfo/python-list