#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2004
    Posts
    2
    Rep Power
    0

    Question Making closures in loop ?


    Hi there,

    I want to create a list of functions with something like:

    closures = [lambda x: i*x for i in range(10)]

    so that
    closures[0] = 0*x
    closures[1] = 1*x
    closures[2] = 2*x
    ...
    closures[9] = 9*x

    For some reason, all elements seem to bind the last value of i, that is closures[j] = 9*x for all j, not only 9. Any ideas of why does this happen, and how should I make it work as intended ?

    George
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    133
    Rep Power
    11
    That is how it is bound.

    Check what jeremy has got to say.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    You can get it to work the way you want by passing in i as a default parameter, i.e.:

    Code:
    >>> closures = [lambda x, i=i: i*x for i in range(10)]
    >>> closures[1](2)
    2
    >>> closures[4](2)
    8
    This was the standard way to simulate closures in Python prior to 2.1, when it did not have the new scoping rules.

    Dave - The Developers' Coach
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2004
    Posts
    2
    Rep Power
    0
    I was sure there was a way around it; thanks a lot Dave !

    George

IMN logo majestic logo threadwatch logo seochat tools logo