problem with lambda / closures

Discussion in 'Python' started by Louis Steinberg, Nov 30, 2009.

  1. I have run into what seems to be a major bug, but given my short
    exposure to Python is probably just a feature:

    running
    Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)
    [GCC 4.0.1 (Apple Inc. build 5493)] on darwin

    with file foo.py containing:

    ============================== clip here ============
    def p(d):
    print d


    l=[ ]
    for k in [1,2,3]:
    l.append(lambda : p(k))

    for f in l:
    f()

    ============================== clip here ============
    I get output
    3
    3
    3
    instead of
    1
    2
    3
    which I would expect. Can anyone explain this or give me a
    workaround? Thank you
    Louis Steinberg, Nov 30, 2009
    #1
    1. Advertising

  2. Louis Steinberg wrote:

    > I have run into what seems to be a major bug, but given my short
    > exposure to Python is probably just a feature:



    Yes, it works as advertised :-/


    > which I would expect. Can anyone explain this or give me a workaround?


    like this?


    > def p(d):
    > print d
    >
    >
    > l=[ ]
    > for k in [1,2,3]:
    > l.append(lambda k=k: p(k))
    >
    > for f in l:
    > f()
    Marco Mariani, Nov 30, 2009
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Roman Suzi
    Replies:
    13
    Views:
    595
    Bengt Richter
    Jan 7, 2005
  2. Terry Reedy

    Re: problem with lambda / closures

    Terry Reedy, Nov 30, 2009, in forum: Python
    Replies:
    2
    Views:
    277
    Terry Reedy
    Dec 1, 2009
  3. Steve Dogers

    lambda vs non-lambda proc

    Steve Dogers, Mar 30, 2009, in forum: Ruby
    Replies:
    1
    Views:
    161
    Sean O'Halpin
    Mar 30, 2009
  4. Aldric Giacomoni

    Closures / lambda question

    Aldric Giacomoni, Oct 28, 2009, in forum: Ruby
    Replies:
    12
    Views:
    177
    Waldemar Dick
    Oct 30, 2009
  5. Stu
    Replies:
    31
    Views:
    358
    Steve Klabnik
    Apr 27, 2011
Loading...

Share This Page