This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: odd behaviour when making lists of lambda forms
Type: Stage:
Components: Interpreter Core Versions: Python 2.3
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: jhidding, rhettinger
Priority: normal Keywords:

Created on 2005-10-13 20:56 by jhidding, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg26589 - (view) Author: Johan Hidding (jhidding) Date: 2005-10-13 20:56
Hi,

I don't know if this is really a bug, but it is odd. I
tried to make a list of lambda forms like in the
following example, but the functions thus created don't
really do what I expect.

**************
Python 2.3.5 (#2, Jun 19 2005, 13:28:00) 
[GCC 3.3.6 (Debian 1:3.3.6-6)] on linux2
Type "help", "copyright", "credits" or "license" for
more information.
>>> p = [lambda t: t**n for n in range(6)]
>>> p[0](2)
32
>>> p
[<function <lambda> at 0xb7cece64>, <function <lambda>
at 0xb7cf10d4>, <function <lambda> at 0xb7cf1b1c>,
<function <lambda> at 0xb7cf1b54>, <function <lambda>
at 0xb7cf1b8c>, <function <lambda> at 0xb7cf1bc4>]
>>> p[1](2)
32
>>> p[1](5)
3125
****************
While:
****************
>>> q = [lambda t: 1, lambda t: t, lambda t: t**2,
lambda t: t**3, lambda t: t**4]
>>> q[0](4)
1
>>> q[1](4)
4
>>> q[2](4)
16
***************

I tried creating the list using a for loop, but it
shows the same weird behaviour. Also any attempt to put
the lambda form in an object didn't give a cure.

say: 
Wrap(lambda x: x**2)
creates a callable object storing the lambda form as a
data member.
****
>>> j = [Wrap(lambda t: t**n) for n in range(5)]
>>> j[0](1)
1
>>> j[0](3)
81
>>> j[0](5)
625
****

Both Python 2.3 and 2.4 show this behaviour. Am I
completely overlooking something, or...?

kind regards,

Johan Hidding
Groningen, the Netherlands
msg26590 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2005-10-14 14:41
Logged In: YES 
user_id=80475

Try this:
    p = [lambda t, n=n: t**n for n in range(6)]

History
Date User Action Args
2022-04-11 14:56:13adminsetgithub: 42480
2005-10-13 20:56:32jhiddingcreate