Why lambda in loop requires default?

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Sun Mar 27 10:16:23 EDT 2016


gvim writes:

> Given that Python, like Ruby, is an object-oriented language why
> doesn't this:
>
> def m():
>   a = []
>   for i in range(3): a.append(lambda: i)
>   return a
>
> b = m()
> for n in range(3): print(b[n]())  # =>  2  2  2

I'm going to suggest two variations that may or may not work for you,
with very brief glosses. Just ignore them if you don't see their
relevance.

First, consider:

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

b = w()
for f in b: print(f()) # => ! ! !

(Those functions depend on the i in the loop.)

> lambda i=i: i
>
> ... is needed to make it work in Python. Just wondered why?

And second, consider: lambda x=i: x

(Those functions are independent of the i in the loop.)



More information about the Python-list mailing list