Python traps ยท Python

This Python code is WRONGPRO

Watch the video

Removing from a list while looping over it skips items. Two clean fixes.

# This Python code is WRONG ๐Ÿ˜ณ โ€” removing from a list while looping over it skips items.
nums = [2, 4, 6, 7, 8]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)   # [4, 7] ?!  (4 and 8 survived)

# Fix: loop over a COPY
nums = [2, 4, 6, 7, 8]
for n in nums[:]:
    if n % 2 == 0:
        nums.remove(n)
print(nums)   # [7] โœ“

# Cleaner fix: build a new list
+ 3 more lines in the app (Pro)
Open code P3 in Pocket Compiler Download the Pocket Compiler app โ€” free

No app yet? Install it, then open the app and type the code P3 in Code Library.