Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #105920

Re: Why lambda in loop requires default?

From Antoon Pardon <antoon.pardon@rece.vub.ac.be>
Newsgroups comp.lang.python
Subject Re: Why lambda in loop requires default?
Date 2016-03-28 22:26 +0200
Message-ID <mailman.111.1459196880.28225.python-list@python.org> (permalink)
References <56F73B60.9020603@gmail.com>

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Why lambda in loop requires default? Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2016-03-28 22:26 +0200

csiph-web