Mutating a List Doesn't Need nonlocal, Rebinding Does
def make_tracker():
log = []
total = 0
def record(x):
log.append(x)
total += x
return total
return record, log
track, log = make_tracker()
track(5)
Now compare with this version, where the only change is one added line inside record:
def make_tracker():
log = []
total = 0
def record(x):
nonlocal total
log.append(x)
total += x
return total
return record, log
track, log = make_tracker()
track(5)
What happens in each case?
Sign in to answer questions and track your progress
Sign In