Title: Example code becomes invalid for "Why do lambdas defined in a loop with different values all return the same result?"
Type: enhancement Stage: resolved
Components: Documentation Versions: Python 3.6
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: docs@python Nosy List: docs@python, eric.smith, iMath
Priority: normal Keywords:

Created on 2017-04-09 06:16 by iMath, last changed 2017-04-09 15:38 by eric.smith. This issue is now closed.

Messages (2)
msg291353 - (view) Author: Philip Lee (iMath) Date: 2017-04-09 06:16
There example code here becomes invalid
>>> squares = []
>>> for x in range(5):
	squares.append(lambda: x**2)

>>> squares
[<function <lambda> at 0x01FB7A08>, <function <lambda> at 0x01F82390>, <function <lambda> at 0x01FBA3D8>, <function <lambda> at 0x01FBA420>, <function <lambda> at 0x01FBA468>]

There returned value is a List of lambda functions, not numbers
msg291379 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2017-04-09 14:29
That's consistent with the example: it's showing you how to create a list of functions, that when called, return squares.

"This gives you a list that contains 5 lambdas that calculate x**2"

Maybe "squares" isn't the most awesome name, but I think if you read the example in its entirety, it's all consistent and correct.
Date User Action Args
2017-04-09 15:38:34eric.smithsetstatus: open -> closed
resolution: not a bug
stage: resolved
2017-04-09 14:29:22eric.smithsetnosy: + eric.smith
messages: + msg291379
2017-04-09 06:16:55iMathcreate