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)?
- A. for x in nums: if x % 2 == 0: nums.remove(x)
- B. nums[:] = [x for x in nums if x % 2]
- C. nums = list(filter(lambda x: x % 2, nums))
- 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
- What is printed? python import sys a = [] b = a c = [a, a] print(sys.getrefcount(a) - sys.getrefcount([]) >= 3, c[0] is c[1], [a] == [b])
- What is printed? python x = (1, 2, 3) y = x + (4,) z = x 0 print(len(y), z, x.count(2), x.index(3), 3 in x)
- What is printed? python s = "a1b22c333" digits = "".join(ch for ch in s if ch.isdigit()) letters = [ch for ch in s if ch.isalpha()]…
- What is printed? python def f(n, memo={}): if n in memo: return memo[n] r = n if n < 2 else f(n - 1) + f(n - 2) memo[n] = r return r f(10)…
- What is printed? python def f(): x = 1 def g(): return x x = 2 return g def h(): for x in [1, 2]: pass return lambda: x print(f()(), h()())
- What is printed? python class Node: def init(self, v, nxt=None): self.v, self.nxt = v, nxt def iter(self): n = self while n: yield n.v n =…