I find Python's name-bindings to be especially confusing at times. In the following code:
list_of_funcs = [] for i in range(10): def f(): print i list_of_funcs.append(f) for f in list_of_funcs: f()
The output will be:
9 9 9 9 9 9 9 9 9
Because the name i is bound to the loop, and not to the function. To get a sequence of numbers, we'd have to do as follows:
i
list_of_funcs = [] for i in range(10): def make_f(n): def f(): print n return f list_of_funcs.append(make_f(i)) for f in list_of_funcs: f()
The function make_f(n) creates a new binding. A new n is bound at every call to make_f(n), so the values are kept.
make_f(n)
n
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I find Python's name-bindings to be especially confusing at times.
In the following code:
The output will be:
Because the name
i
is bound to the loop, and not to the function. To get a sequence of numbers, we'd have to do as follows:The function
make_f(n)
creates a new binding. A newn
is bound at every call tomake_f(n)
, so the values are kept.