[ python-Bugs-1326195 ] odd behaviour when making lists of lambda forms

SourceForge.net noreply at sourceforge.net
Fri Oct 14 16:41:45 CEST 2005


Bugs item #1326195, was opened at 2005-10-13 15:56
Message generated for change (Comment added) made by rhettinger
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1326195&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Interpreter Core
Group: Python 2.3
>Status: Closed
>Resolution: Invalid
Priority: 5
Submitted By: Johan Hidding (jhidding)
Assigned to: Nobody/Anonymous (nobody)
Summary: odd behaviour when making lists of lambda forms

Initial Comment:
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


----------------------------------------------------------------------

>Comment By: Raymond Hettinger (rhettinger)
Date: 2005-10-14 09:41

Message:
Logged In: YES 
user_id=80475

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



----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1326195&group_id=5470


More information about the Python-bugs-list mailing list