Skip to content
Onsite

Output: removing items from a list while iterating over it

MediumP2Output

What does this code print?

1nums = [1, 2, 2, 3, 4]
2for n in nums:
3 if n % 2 == 0:
4 nums.remove(n)
5print(nums)
6
7nums = [1, 2, 2, 3, 4]
8for n in nums[:]:
9 if n % 2 == 0:
10 nums.remove(n)
11print(nums)
Saved automatically

One line per print, as Python prints it. An uncaught exception as its last traceback line, for example ZeroDivisionError: division by zero.

Hints

Saved automatically