On 9/6/07, <b class="gmail_sendername">Chris Johnson</b> <<a href="mailto:effigies@gmail.com">effigies@gmail.com</a>> wrote:<div><span class="gmail_quote"></span><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
What I want to do is build an array of lambda functions, like so:<br><br>a = [lambda: i for i in range(10)]<br><br>(This is just a demonstrative dummy array. I don't need better ways to<br>achieve the above functionality.)
<br><br>print [f() for f in a]<br><br>results in: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]<br>rather than the hoped for: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]<br><br>Clearly, lambda is returning the object i, which is left at the last<br>
value of range(10). The following is my solution.<br><br>t = lambda i: lambda: i<br>a = [t(i) for i in range(10)]<br><br>or the somewhat more terse:<br><br>a = [(lambda i: lambda: i)(i) for i in range(10)]<br><br>This gives the behavior which, intuitively, I expected from the
<br>original syntax. So my questions are:<br>1) Does this make sense as what should be done here? That is, would<br>this be the behavior you'd want more often than not? As I said,<br>intuitively, I would think the lambda would treat the iterator
<br>variable as a constant in this context.<br>2) Is there a better or preferred method than the one I've found?</blockquote><div><br>A more explicit example of your solution would be:<br>    >>> def gen(i):<br>
    ...     return lambda: i # bind to the i passed in<br>    ... <br>    >>> l = [gen(i) for i in range(10)]<br>    >>> [f() for f in l]<br>    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]<br><br>Your initial lambda: i creates a function that binds to i in the current scope. When you wrapped that in another lambda you were creating a new scope with a new value of i and returning a function bound to that value for i. 
<br><br>Take a look at closures:<br>  <a href="http://www.ibm.com/developerworks/linux/library/l-prog2.html#h1">http://www.ibm.com/developerworks/linux/library/l-prog2.html#h1</a><br>  <a href="http://ivan.truemesh.com/archives/000392.html">
http://ivan.truemesh.com/archives/000392.html</a><br><br><br>David<br>--<br><a href="http://www.traceback.org">http://www.traceback.org</a><br></div></div><br>