Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #105920 > unrolled thread
| Started by | Antoon Pardon <antoon.pardon@rece.vub.ac.be> |
|---|---|
| First post | 2016-03-28 22:26 +0200 |
| Last post | 2016-03-28 22:26 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Why lambda in loop requires default? Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2016-03-28 22:26 +0200
| From | Antoon Pardon <antoon.pardon@rece.vub.ac.be> |
|---|---|
| Date | 2016-03-28 22:26 +0200 |
| Subject | Re: Why lambda in loop requires default? |
| Message-ID | <mailman.111.1459196880.28225.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web