Search⌘ K

Can I Call You Later?

Explore how Python's closure mechanism interacts with loop variables, causing functions defined in loops to reference the same variable. Learn to predict outputs and apply techniques such as passing loop variables as default arguments or using lambda functions to capture desired values. This lesson helps you avoid common mistakes with function references and closures in Python loops.

We'll cover the following...

Should you call the functions first and then append the result, or append the functions and then call them later? Is there any difference? Let’s find out.

1.

Can you predict the output of the following code?

Python 3.5
funcs = []
results = []
for x in range(7):
def some_func():
return x
funcs.append(some_func)
results.append(some_func()) # note the function call here
funcs_results = [func() for func in funcs]
print(results)
print(funcs_results)

Even when the values of x were ...