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


Groups > comp.lang.python > #105856

Re: Why lambda in loop requires default?

From Terry Reedy <tjreedy@udel.edu>
Newsgroups comp.lang.python
Subject Re: Why lambda in loop requires default?
Date 2016-03-27 12:12 -0400
Message-ID <mailman.89.1459095177.28225.python-list@python.org> (permalink)
References <56F73B60.9020603@gmail.com>

Show all headers | View raw


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

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


Thread

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

csiph-web