Question about 'print' in a loop

dieter dieter at handshake.de
Thu Nov 19 02:31:04 EST 2015


fl <rxjwg98 at gmail.com> writes:

> Hi,
>
> From previous post, I get many helpful replies. Now I have a new question
> when I run this example code:
>
>
> ---------
> sq=[]
> for xx in range(5):
>     print 'here'
>     sq.append(lambda:xx**2)
> ...
> sq[2]()
> Out[151]: 16
>
> sq[3]()
> Out[152]: 16
> /////

Same reason as in your previous thread: variables in (the body of) function
definitions (and "lambda"s, which are functions definitions, too) are
resolved/dereferenced at call time, not at function definition time.




More information about the Python-list mailing list