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

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to