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. Advertisements

  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. Advertisements

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:
    821
    Bengt Richter
    Jan 7, 2005
  2. alain

    problem with closures

    alain, Dec 6, 2006, in forum: Python
    Replies:
    1
    Views:
    319
    Gerard Brunick
    Dec 7, 2006
  3. Tom Plunket

    Problem understanding how closures work

    Tom Plunket, Dec 12, 2006, in forum: Python
    Replies:
    3
    Views:
    351
    Tom Plunket
    Dec 12, 2006
  4. Terry Reedy

    Re: problem with lambda / closures

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

    lambda vs non-lambda proc

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

    Closures / lambda question

    Aldric Giacomoni, Oct 28, 2009, in forum: Ruby
    Replies:
    12
    Views:
    319
    Waldemar Dick
    Oct 30, 2009
  7. Stu
    Replies:
    31
    Views:
    732
    Steve Klabnik
    Apr 27, 2011
  8. Haochen Xie
    Replies:
    4
    Views:
    435
    Haochen Xie
    Mar 17, 2013
Loading...