0

In this code:

> python
>>> a = []
>>> for i in range(2):
...     def printer():
...          print i
...     a.append(printer)
...
>>> a
[<function printer at 0x01EDE330>, <function printer at 0x01EDE2F0>]
>>> a[0]()
1
>>> a[1]()
1
>>>
>>> a[0] == a[1]
False

it appears that I made two different functions, and stored them in the array a[].

I don't understand why the functions appear to be different, but the result of each function is not. I would have thought either the functions would be the same (IE the second iteration would redefine the one from the first), or the functions would be different and the result would be different (0 and 1 respectively).

I hoping for and expecting the latter...

GreenAsJade
  • 14,459
  • 11
  • 63
  • 98
  • @Martijn Pieters: Thanks for quickly pointing me in in the right direction, and for your excellent answer in the other question. I wonder if you would consider taking this question off "duplicate" and allowing an answer here. The reason is that while it's a great answer, it's a convoluted question, and so the workaround examples are also convoluted. If you don't know about partials already, its a bit tricky to untangle the workaround from the question code. An answer here, of the same form, could allow for more clarity. – GreenAsJade Sep 26 '15 at 23:30
  • There are more duplicates linked from the sidebar, many with answers. – Martijn Pieters Sep 26 '15 at 23:32
  • There are no duplicates of this question appearing in my sidebar, other than the one you linked to. – GreenAsJade Sep 27 '15 at 03:08
  • Sorry, I meant the one I linked you to. There currently are 87 posts linked there http://stackoverflow.com/questions/linked/12423614?lq=1 – Martijn Pieters Sep 27 '15 at 09:43
  • Hah - my mistake, thanks! – GreenAsJade Sep 28 '15 at 04:53

0 Answers0