Why lambda in loop requires default?

Antoon Pardon antoon.pardon at rece.vub.ac.be
Mon Mar 28 16:26:48 EDT 2016


Op 27-03-16 om 03:46 schreef gvim:
> Given that Python, like Ruby, is an object-oriented language why doesn't this:

It has nothing to do with being object-oriented but by how scopes are used

> def m():
>   a = []
>   for i in range(3): a.append(lambda: i)
>   return a

Python doesn't create a new scope for the suite of the for loop. If you want an
intermediate scope, you have to provide it your self. Like the following.

def m():
    a = []
    for i in range(3):
        a.append((lambda i: (lambda : i))(i))
    return a

> b = m()
> for n in range(3): print(b[n]())  # =>  2  2  2
> 
> ... work the same as this in Ruby:
> 
> def m
>   a = []
>   (0..2).each {|i| a << ->(){i}}
>   a
> end

I don't know ruby but I guess the block creates a new scope and
thus running the block is like calling an anonymous function.
So the i in each run of the block is a new instantiation of the
variable instead of being the same variable.

-- 
Antoon Pardon




More information about the Python-list mailing list