ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
a = [5, 1, 4]
b = a
a = sorted(a)
c = a.copy()
c.reverse()
print(a, b, c)
  1. A. [5, 1, 4] [5, 1, 4] [1, 4, 5]
  2. B. [1, 4, 5] [5, 1, 4] [1, 4, 5]
  3. C. [1, 4, 5] [5, 1, 4] [5, 4, 1]
  4. D. [1, 4, 5] [1, 4, 5] [5, 4, 1]

Correct answer: C. [1, 4, 5] [5, 1, 4] [5, 4, 1]

sorted returns a new list, so a is rebound to a new object and b still refers to the original [5, 1, 4]. copy() makes a fresh list, and reverse() flips only that copy.

More Python Programming questions

Exams that ask this topic