Practice question · True or false
In Python, a = [1,2,3] then b = a then b.append(4) leaves a with three elements.
Hints
- Does assignment copy the list or name it?
- Both names refer to one object.
Show the answer
False
Why
False. b = a binds a second name to the same list, so a has four elements afterwards. Only an explicit copy — a[:], list(a), copy.deepcopy for nested data — makes an independent object. This is the single most common source of surprise in Python and the reason is differs from ==.
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
- The operator + adds two numbers but joins two strings. Sort each expression by what it evaluates to.
- 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…
- Order what the machine does when it runs the single line x = x + 1, given that x currently holds 7.