Could you explain why the following generates 4 same elements list?

Ian Kelly ian.g.kelly at gmail.com
Wed Nov 18 19:47:51 EST 2015


On Wed, Nov 18, 2015 at 5:05 PM, fl <rxjwg98 at gmail.com> wrote:
> 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]
>
>
> I have tried to simplify the above code to an easy understanding form,
> but fails. Either the modified code does not work, or it does not show
> relation to the original code.
>
> Could you explore it a little for me to understand it easier?

https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result



More information about the Python-list mailing list