ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
nums = [5, 3, 8]
nums2 = nums
nums += [1]
nums3 = nums[:]
nums3.pop()
print(nums2, nums3)
  1. A. [5, 3, 8, 1] [5, 3, 8]
  2. B. [5, 3, 8] [5, 3, 8]
  3. C. [5, 3, 8, 1] [5, 3, 8, 1]
  4. D. [5, 3, 8] [5, 3]

Correct answer: A. [5, 3, 8, 1] [5, 3, 8]

+= on a list extends the same object, so nums2 sees the new item too. nums3 is an independent copy, and pop removes its last value 1, leaving [5, 3, 8].

More Python Programming questions

Exams that ask this topic