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


Groups > comp.lang.python > #105856 > unrolled thread

Re: Why lambda in loop requires default?

Started byTerry Reedy <tjreedy@udel.edu>
First post2016-03-27 12:12 -0400
Last post2016-03-27 12:12 -0400
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.


Contents

  Re: Why lambda in loop requires default? Terry Reedy <tjreedy@udel.edu> - 2016-03-27 12:12 -0400

#105856 — Re: Why lambda in loop requires default?

FromTerry Reedy <tjreedy@udel.edu>
Date2016-03-27 12:12 -0400
SubjectRe: Why lambda in loop requires default?
Message-ID<mailman.89.1459095177.28225.python-list@python.org>
On 3/26/2016 9:46 PM, gvim wrote:
> 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
>
>def echo_i: return i

> b = m()
> for n in range(3): print(b[n]())  # =>  2  2  2

)  # =>  2  2  2
>
> ... work the same as this in Ruby:
>
> def m
>    a = []
>    (0..2).each {|i| a << ->(){i}}
>    a
> end
>
> aa = m
> (0..2).each {|n| puts aa[n].()}  # =>  0  1  2

Since Python came first, and Ruby was partly inspired by and derived 
from Python, perhaps you should ask Ruby folk why it does not work the 
same as Python.  (Because Matz wanted it different.)

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

Your Python def m is essentially equivalent to

def m():
   def echo_i(): return i
   i = 2
   return [echo_i]*3

-- 
Terry Jan Reedy

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web