[Python-Dev] 2.5 and beyond

Terry Reedy tjreedy at udel.edu
Sat Jul 1 06:27:16 CEST 2006


"Giovanni Bajo" <rasky at develer.com> wrote in message 
news:020c01c69ca1$754c7310$d1b12997 at bagio...
> Yes but:
>
>>>> a = []
>>>> for i in range(10):
> ...     a.append(lambda: i)
> ...
>>>> print [x() for x in a]
> [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
>
> This subtle semantic of lambda is quite confusing, and still forces 
> people to
> use the "i=i" trick.

The 'subtle sematic' had nothing to do with lambda but with Python 
functions.

The above is exactly equivalent (except the different .funcname) to

a = []
for i in range(10):
    def f(): return i
    a.append(f)
    del f

That should be equally confusing (or not), and equally requires the 'i=i' 
trick (or not).

As is, either function definitiion is a constant and the loop makes useless 
duplicates.  Either form would have the same effect is hoisted out of the 
loop.

Terry Jan Reedy





More information about the Python-Dev mailing list