← Back to Python, page 4

python-0078 · Easy fresher

What does this program print, given that integers are immutable and lists are mutable?

Rebinding an integer parameter inside a function does not change the caller's variable, because the function only rebinds its local name. Mutating a list through a parameter does change the caller's list, because both names refer to the same object. Assigning a new list to the parameter, rather than mutating it, again leaves the caller unchanged.

Full answer
python
def bump(n, items, other):
    n += 1
    items.append(n)
    other = other + [n]
    return n

count, log, extra = 1, [], []
result = bump(count, log, extra)
print(count, result, log, extra)

Output:

text
1 2 [2] []

n += 1 makes the local n refer to a new integer 2; count outside is still 1. items.append mutates the list object shared with log, so log becomes [2]. other = other + [n] builds a new list and binds only the local name, so extra stays empty. Python passes references to objects, and what matters is whether the function mutates the object or rebinds the name.

python
def bump(n, items, other):
    n += 1
    items.append(n)
    other = other + [n]
    return n

count, log, extra = 1, [], []
result = bump(count, log, extra)
print(count, result, log, extra)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Parameters are names bound to the caller's objects
  • Rebinding a parameter is local
  • Mutation is visible to the caller
  • + creates a new list, append mutates
  • Ints and strings are immutable

Common mistakes

  • Expecting n += 1 to change the caller's int
  • Assuming other + [...] mutates the list

Follow-ups

  • What would other += [n] do instead?
  • How do you avoid mutating an argument?

Tips

  • Separate rebinding from mutation