Common Mistakes in Python Loops and How to Avoid Them
Share
Loops are core in Python, but even seasoned developers run into issues. Let’s look at typical pitfalls and ways around them.
- Infinite loop: Common in while when condition doesn’t change (e.g., while True without break). Avoid: add a counter or variable check inside.
- Wrong range usage: range(1, 10) excludes 10. If inclusive, range(1, 11). Check: print(list(range(1, 10))) → [1,2,3,4,5,6,7,8,9].
- Modifying list during iteration: for item in my_list: my_list.remove(item) may skip items. Avoid: copy my_list[:] or list comprehension [item for item in my_list if not condition].
- Unnecessary loops: Instead of nested for for filtering — use comprehensions or filter(). More efficient and readable.
- Ignoring enumerate: for i in range(len(my_list)): print(i, my_list[i]) is old. Better: for i, item in enumerate(my_list): print(i, item).

- While with input errors: While without input error check. Add try-except for ValueError.
- Misusing break/continue: Break exits loop, continue skips iteration. Test in small example.
- Forgotten indents: Python needs 4 spaces. Without — IndentationError.
- Underusing zip: For parallel iteration: for a, b in zip(list1, list2).
- Suboptimal loops for big data: For millions of items — use generators or numpy.

These tips come from real projects. For practice — check Zenith Flow.