AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumpythonlistsmutability

~90s

Aliasing against slicing

What does this Python program print?

a = [1, 2, 3]
b = a
b.append(4)
c = a[:]
c.append(5)
print(len(a), len(b), len(c))
Show the answer and the worked solution

Correct answer: D.

4 4 5

Worked solution

  1. b = a makes b another name for the same list, so b.append(4) leaves a single list [1, 2, 3, 4] of length 4 that both names see.
  2. c = a[:] takes a copy of that list as it stands, so c starts as [1, 2, 3, 4].
  3. c.append(5) affects only the copy, giving lengths 4, 4 and 5, printed as 4 4 5.

Answer: 4 4 5.

The idea

Assignment binds a second name to the same object; slicing, list() or copy() build a new one. Knowing which of the two you have written decides whether a mutation is shared.

Shortcut. a and b name one list, so their lengths must match, ruling out "3 4 5"; c copies the list after the 4 is appended, so it ends with 5 elements.

Common trap. "3 4 5" tempts as a neat staircase from reading every line as making its own list, but b = a copies nothing, so a and b must report the same length.

Aliasing against slicing — Aptitude Question

Aliasing against slicing: What does this Python program print? Answer and worked solution on CodeKairo.

Question

What does this Python program print?

a = [1, 2, 3]
b = a
b.append(4)
c = a[:]
c.append(5)
print(len(a), len(b), len(c))

Options

  1. 3 3 4
  2. 3 4 5
  3. 4 4 4
  4. 4 4 5
Show the answer and the worked solution

Correct answer: D. 4 4 5

Worked solution

  1. b = a makes b another name for the same list, so b.append(4) leaves a single list [1, 2, 3, 4] of length 4 that both names see.
  2. c = a[:] takes a copy of that list as it stands, so c starts as [1, 2, 3, 4].
  3. c.append(5) affects only the copy, giving lengths 4, 4 and 5, printed as 4 4 5.

Answer: 4 4 5.

The idea

Assignment binds a second name to the same object; slicing, list() or copy() build a new one. Knowing which of the two you have written decides whether a mutation is shared.

Shortcut. a and b name one list, so their lengths must match, ruling out "3 4 5"; c copies the list after the 4 is appended, so it ends with 5 elements.

Common trap. "3 4 5" tempts as a neat staircase from reading every line as making its own list, but b = a copies nothing, so a and b must report the same length.

All Programming Fundamentals questions · placement mock tests