ProgrammingHardGATE CS · Product-company placement

Which is the safest way to remove every even number from a list `nums` in place (so that other references to the same list see the change)?

  1. A. for x in nums: if x % 2 == 0: nums.remove(x)
  2. B. nums[:] = [x for x in nums if x % 2]
  3. C. nums = list(filter(lambda x: x % 2, nums))
  4. D. for i in range(len(nums)): if nums[i] % 2 == 0: del nums[i]

Correct answer: B. nums[:] = [x for x in nums if x % 2]

Slice assignment replaces the contents of the same list object. Removing while iterating skips elements, deleting by a precomputed index range runs past the shrinking end (IndexError), and rebinding the name to a new list (filter version) is never seen by other references.

More Python Programming questions

Exams that ask this topic