473,395 Members | 1,972 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

scoping with lambda in loops

I was bitten by a bug today that depended on how lambda works. It took
me quite a while to realize what was going on.

First, I made multiple lambda functions inside a loop, each of which
depended on the current loop variable.
a = []
for index in range(5): a.append(lambda: index)
Now, see if you can guess what the output was for each of the
functions in the list a: a[0](), a[1](), a[2](), a[3](), a[4]()

I had expected it to be (0, 1, 2, 3, 4), but actually, it's:

(4, 4, 4, 4, 4)

This really surprised me. I guess what is happening is that each
lambda knows what the context of execution is where it was defined,
and doesn't actually evaluate until the function is called, and when
it does evaluate, it uses the current value of the variable. Is this
related to static scoping? A similar thing would happen if you defined
a nested function that used a variable declared in the outer function,
then changed that variable, and called the nested function.

Can someone recommend a way to code around this gotcha? I'm having
trouble. I want the functions created inside the loop to execute with
the value of the loop index at the moment when the function is made.
Jul 18 '05 #1
8 2606
On 16 Sep 2003 14:38:16 -0700, rumours say that im******@telus.net (Ian
McMeans) might have written:
First, I made multiple lambda functions inside a loop, each of which
depended on the current loop variable.
a = []
for index in range(5): a.append(lambda: index)

Now, see if you can guess what the output was for each of the
functions in the list a: a[0](), a[1](), a[2](), a[3](), a[4]()
I had expected it to be (0, 1, 2, 3, 4), but actually, it's:

(4, 4, 4, 4, 4)

This really surprised me. I guess what is happening is that each
lambda knows what the context of execution is where it was defined,
and doesn't actually evaluate until the function is called, and when
it does evaluate, it uses the current value of the variable. Is this
related to static scoping? A similar thing would happen if you defined
a nested function that used a variable declared in the outer function,
then changed that variable, and called the nested function.

Can someone recommend a way to code around this gotcha? I'm having
trouble. I want the functions created inside the loop to execute with
the value of the loop index at the moment when the function is made.


I think this is a FAQ (perhaps it was FAQ 6.10?), and you can find many
threads on the subject if you do a search on groups.google.com.

The typical way to deal with this, IIRC, is to change your lambda
declaration into:
a.append(lambda index=index: index)


so that index gets evaluated at definition time.
--
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.
Jul 18 '05 #2
Ian McMeans wrote:
a = []
for index in range(5): a.append(lambda: index) [...] Can someone recommend a way to code around this gotcha? I'm having
trouble. I want the functions created inside the loop to execute with
the value of the loop index at the moment when the function is made.


intuitively, i would think this should do the trick:
a = []
for index in range(5):

.... a.append(lambda x=index: x)

and testing shows that it does indeed.

but the reason why is rather vague to me, (i'm still rather new at this...)
so perhaps i should think a little more before trying to explain. (and i'm
sure someone else will come and do it better than i ever could.)

--
Joost Kremers
since when is vi an editor? a discussion on vi belongs in
comp.tools.unusable or something... ;-)
Jul 18 '05 #3
Ian> First, I made multiple lambda functions inside a loop, each of which
Ian> depended on the current loop variable.
a = []
for index in range(5):
a.append(lambda: index)

Ian> Now, see if you can guess what the output was for each of the
Ian> functions in the list a: a[0](), a[1](), a[2](), a[3](), a[4]()

Ian> I had expected it to be (0, 1, 2, 3, 4), but actually, it's:

Ian> (4, 4, 4, 4, 4)

Ian> This really surprised me.

Suppose you did it this way:

a = []
for index in range(5):
def foo():
return index
a.append(foo)

What result would you expect now, and why?

--
Andrew Koenig, ar*@acm.org
Jul 18 '05 #4
In article <7f**************************@posting.google.com >,
im******@telus.net (Ian McMeans) wrote:
First, I made multiple lambda functions inside a loop, each of which
depended on the current loop variable.
a = []
for index in range(5): a.append(lambda: index)
Now, see if you can guess what the output was for each of the
functions in the list a: a[0](), a[1](), a[2](), a[3](), a[4]()

I had expected it to be (0, 1, 2, 3, 4), but actually, it's:

(4, 4, 4, 4, 4)

This really surprised me. I guess what is happening is that each
lambda knows what the context of execution is where it was defined,
and doesn't actually evaluate until the function is called, and when
it does evaluate, it uses the current value of the variable. Is this
related to static scoping?


It's related to closures. If you're using lambda, you're probably a
lisp programmer, and should know all about closures. Creating a
function object with def or lambda, within an outer function scope,
creates a closure for that outer function call. The inner function's
accesses to variables from the outer function will return the
most-recently-updated binding from the closure. If you call the outer
function again, you will get a different unrelated closure.

If you the inner function to have its own local variable that stores
some expression value as it existed at the creation time of the inner
function, rather than re-evaluating the expression whenever the inner
function is called, the standard way is to use a defaulted keyword
parameter:

a = []
for index in range(5):
a.append(lambda index=index: index)

or maybe more concisely

a = [lambda index=index: index for index in range(5)]

--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
Jul 18 '05 #5
> a = []
for index in range(5):
a.append(lambda index=index: index)

or maybe more concisely

a = [lambda index=index: index for index in range(5)]


You know how Python is supposed to be executable pseudocode? Well that
stuff is farking ugly. If I handed pseudocode like that into any TA in one
of my classes, I'd be toast. Is there any way to do that in a legible
manner?
Jul 18 '05 #6
"martin z" <px**@hotmail.com> wrote in message
news:Kv******************@news04.bloor.is.net.cabl e.rogers.com...
a = []
for index in range(5):
a.append(lambda index=index: index)

or maybe more concisely

a = [lambda index=index: index for index in range(5)]
You know how Python is supposed to be executable pseudocode? Well that
stuff is farking ugly. If I handed pseudocode like that into any TA in

one of my classes, I'd be toast. Is there any way to do that in a legible
manner?


The following reads pretty well to me:
produce_value = lambda value: lambda: value
a = [produce_value(index) for index in range(5)]
a[3]()

3

Dave

Jul 18 '05 #7
In article <Kv******************@news04.bloor.is.net.cable.ro gers.com>,
"martin z" <px**@hotmail.com> wrote:
a = []
for index in range(5):
a.append(lambda index=index: index)

or maybe more concisely

a = [lambda index=index: index for index in range(5)]


You know how Python is supposed to be executable pseudocode? Well that
stuff is farking ugly. If I handed pseudocode like that into any TA in one
of my classes, I'd be toast. Is there any way to do that in a legible
manner?


How about this:

def makefunction(x):
def thefunction():
return x
return thefunction

a = map(makefunction, range(5))

The identifiers are still a little uninformative, but it's hard to do
better without more information from the original poster...

--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
Jul 18 '05 #8
im******@telus.net (Ian McMeans) writes:
a = []
for index in range(5): a.append(lambda: index)
Now, see if you can guess what the output was for each of the
functions in the list a: a[0](), a[1](), a[2](), a[3](), a[4]()
I had expected it to be (0, 1, 2, 3, 4), but actually, it's:

(4, 4, 4, 4, 4)

This really surprised me. I guess what is happening is that each
lambda knows what the context of execution is where it was defined,
and doesn't actually evaluate until the function is called, and when
it does evaluate, it uses the current value of the variable. Is this
related to static scoping?


It's related to _lexical_ scoping. It is called a lexical closure.

As of the time when nested scopes were introduced into Python,
whenever a name is referenced, it is first sought in the local lexical
scope (ie, the bit of text in the local function body); if it is not
found there, it is sought in the closest enclosing lexical scope (the
text of any enclosing functions), and so on; when you run out of
enclosing functions you try global, then builtin scope.

There is no "index" variable in your lambda's local scope, so it has
to resort to using the one in the global scope ... which, by the time
you get around to calling your functions, has been set to 4.
A similar thing would happen if you defined a nested function that
used a variable declared in the outer function, then changed that
variable, and called the nested function.
Yup.
Can someone recommend a way to code around this gotcha?


Make your own local binding. Function call parameters make local
bindings. So, within a lambda, you can achieve this by using a keyword
argument.

lambda index=index:index (or lambda i=index:i)

Now there is a local index and a global index, so the lambda uses the
local one. Because the default value is evaluated at the time the
lambda expression is evaluated, each local index has a value
corresponding to whatever the global index had at the time the lambda
was evaluated.

Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
by: Michele Simionato | last post by:
I have read with interest the recent thread about closures. The funny thing is that the authors are arguing one against the other but I actually agree with all of them and I have a proposal that...
9
by: Darabos Daniel | last post by:
Hi! I was doing something like this: >>> def p( x ): .... print x .... >>> l = >>> for i in range( 5 ): .... l.append( lambda: p( i ) )
7
by: Philip Smith | last post by:
I've read with interest the continuing debate about 'lambda' and its place in Python. Just to say that personally I think its an elegant and useful construct for many types of programming task...
181
by: Tom Anderson | last post by:
Comrades, During our current discussion of the fate of functional constructs in python, someone brought up Guido's bull on the matter: http://www.artima.com/weblogs/viewpost.jsp?thread=98196 ...
30
by: Mike Meyer | last post by:
I know, lambda bashing (and defending) in the group is one of the most popular ways to avoid writing code. However, while staring at some Oz code, I noticed a feature that would seem to make both...
9
by: NevilleDNZ | last post by:
Can anyone explain why "begin B: 123" prints, but 456 doesn't? $ /usr/bin/python2.3 x1x2.py begin A: Pre B: 123 456 begin B: 123 Traceback (most recent call last): File "x1x2.py", line 13,...
26
by: brenocon | last post by:
Hi all -- Compared to the Python I know and love, Ruby isn't quite the same. However, it has at least one terrific feature: "blocks". Whereas in Python a "block" is just several lines of...
2
by: Dan | last post by:
So, I think I understand what python's scoping is doing in the following situation: 9 9 9 9 2 But, I'm wondering what is the easiest (and/or most pythonic) way to
2
by: Joshua Kugler | last post by:
I am trying to use lamdba to generate some functions, and it is not working the way I'd expect. The code is below, followed by the results I'm getting. More comments below that. patterns = (...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.