Data Structures & AlgorithmsEasyWipro · Accenture pattern

What is printed? (Python list aliasing)

What is printed? (Python list aliasing)
a = [1, 2, 3]
b = a
c = a[:]
b.append(4)
c.append(5)
print(a, len(b), len(c))
  1. A. [1, 2, 3, 4, 5] 5 4
  2. B. [1, 2, 3, 4] 4 4
  3. C. [1, 2, 3] 4 4
  4. D. [1, 2, 3, 4] 4 3

Correct answer: B. [1, 2, 3, 4] 4 4

b = a makes b another name for the same list, so appending 4 through b changes a. a[:] is a shallow copy, so appending 5 to c leaves a alone. Both b and c end with 4 elements.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic