DEV Community

Discussion on: What is the most confusing thing to you in Python?

Collapse
 
tmr232 profile image
Tamir Bahar

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:

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.