ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
a = {1, 2, 3}
b = a
b.add(4)
c = a.copy()
c.add(5)
print(a, c)
  1. A. {1, 2, 3} {1, 2, 3, 4, 5}
  2. B. {1, 2, 3, 4} {1, 2, 3, 4, 5}
  3. C. {1, 2, 3, 4} {1, 2, 3, 5}
  4. D. {1, 2, 3} {1, 2, 3, 5}

Correct answer: B. {1, 2, 3, 4} {1, 2, 3, 4, 5}

b = a is an alias, so b.add(4) mutates the same set a refers to, making a {1,2,3,4}. c = a.copy() makes an independent shallow copy of a's current state; adding 5 to c does not affect a.

More Python Programming questions

Exams that ask this topic