Computer Science I / Variables, Expressions, and Types
Practice question · Multiple choice

In Python, a = [1,2,3]; b = a; b.append(4) leaves a with four elements, but a = 5; b = a; b += 1 leaves a at 5. Why do the two behave differently?

Hints
  1. Ask whether an integer can be changed in place at all.
  2. Rebinding a name affects one name. Mutating an object affects everyone holding it.
Show the answer

B. Because append mutates the shared object while += rebinds a local name

Why

The mechanism is identical, a reference is copied both times, and the objects differ: lists are mutable, integers are not. Rebinding touches your name only; mutating touches the object everyone shares. Python calls this call-by-sharing, and confusing it with by-value or by-reference is where the surprise comes from.

Read the lesson: Variables, Expressions, and Types →

Practise Variables, Expressions, and Types

The app has 6 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.

More questions on Variables, Expressions, and Types