Python problem 21 of 30

Removing while looping

  • Python
  • Medium

This code is meant to remove every 2 from the list. What does it actually print, and why? Fix it.

nums = [1, 2, 2, 3]
for n in nums:
    if n == 2:
        nums.remove(n)
print(nums)
Show hint

A for loop over a list walks through index 0, 1, 2 and so on. What happens to the index of every later item when you remove one?

Show solution
# Prints:
# [1, 2, 3]

nums = [1, 2, 2, 3]
nums = [n for n in nums if n != 2]
print(nums)  # [1, 3]

At index 1 the loop finds a 2 and removes it. Everything shifts left, so the second 2 moves into index 1, which the loop has already visited. The loop moves on to index 2 (now the 3) and never sees it.

Do not change a list's length while looping over it. Build a new list instead, or loop over a copy with for n in nums[:].

Want a problem like this every day? See today's problem and keep a streak going.