Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Fix Late Binding in Loop Generated Functions

Learn to build function factories that correctly capture loop variables. Fix the common late-binding bug when creating functions inside loops.

Python practice15 minClosures & Function FactoriesIntermediateLast updated April 13, 2026

Problem statement

When creating functions inside a loop that reference the loop variable, all generated functions can accidentally share the same final value of that variable — a problem known as late binding. Your task is to implement generate_multipliers(factors), which accepts a list of numeric factors and returns a list of functions. Each returned function should take a single argument x and return x multiplied by the factor that was current when that function was created. You must ensure each function captures its own factor (no late binding).

Task

Implement a closure-based factory that returns a list of functions where each function captures the loop variable at creation time (no late-binding issues).

Examples

Basic multipliers

Input

funcs = generate_multipliers([1, 2, 3]) funcs[1](5)

Output

10

The second generated function multiplies by 2, so funcs[1](5) returns 10.

Input format

A single call to generate_multipliers with a list of numeric factors; then a call to one of the returned functions with a numeric input. For tests, expressions like generate_multipliers([2,3])[1](4) are used.

Output format

A single numeric value: the result of calling the selected multiplier function.

Constraints

factors is a list of integers or floats. The returned functions should work for integer and float inputs. Expected length of factors is typically small (<= 1000). Do not use global variables. Implement the closure correctly so each function retains its own factor.

Samples

Sample 1

Input

generate_multipliers([2, 3, 5])[2](4)

Output

20

The third function multiplies by 5, so passing 4 returns 20.