Loops in Python—sounds simple, right? But even experienced programmers make mistakes when working with loops. These small errors can lead to slow performance, unexpected bugs, and even crashes.
Today, I’ll cover four common Python loop mistakes and how to fix them properly. Let’s dive in!
Mistake #1: Modifying a List While Iterating
This is one of the most common pitfalls for beginners in their Python projects. Removing items from a list while iterating can cause unexpected behavior.
Case 1: The "Accidental Success"
Take a look at this example:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num)
print("Accidental Success:", numbers) # Outputs: [1, 3, 5] (but it's just luck)
At first glance, it seems like the loop removed all even numbers correctly. But this is just by chance!
- When
2
is removed, the list shifts left. 3
moves into the position where2
was.- The loop moves to the next index, which now holds
4
, skipping over it entirely.
Open up your own Python editor to see for yourself!
Case 2: The "Fails Badly" Example
numbers = [1, 2, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num)
print("Fails Badly:", numbers) # Incorrect output: [1, 2, 3, 5]
Here, the second 2
was skipped, so it's still in the list!
The Correct Fix: List Comprehension
Instead of modifying the list while looping, use list comprehensions to create a new list:
numbers = [1, 2, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0] # Keeps only odd numbers
print("Corrected Output:", numbers) # Correct output: [1, 3, 5]
Alternative Fix: If you must modify the original list, iterate over a copy instead:
numbers = [1, 2, 2, 3, 4, 5]
for num in numbers[:]: # Iterate over a copy using slicing
if num % 2 == 0:
numbers.remove(num)
print("Fixed Output:", numbers) # [1, 3, 5]
Mistake #2: Using range(len())
Instead of enumerate()
Many beginners write loops like this:
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(i, fruits[i])
While this works, Python has a cleaner way:
for i, fruit in enumerate(fruits):
print(i, fruit) # Cleaner and more readable!
Why Use enumerate()
?
- More readable (no need for
range(len())
). - Avoids off-by-one errors.
- More Pythonic.
Mistake #3: Using while True
Without a Break Condition
Infinite loops can be useful, but without a clear exit condition, they can run forever.
Consider this example:
while True:
user_input = input("Enter 'q' to quit: ")
if user_input == 'q':
break
This works, but if there's a bug in the input logic, it could run indefinitely.
The Safer Approach
Instead of relying on while True
, use a clear loop condition:
user_input = ""
while user_input != "q":
user_input = input("Enter 'q' to quit: ")
This ensures the loop will only run while necessary.
Mistake #4: Looping Over a Dictionary the Hard Way
Many people overcomplicate dictionary iteration:
data = {"name": "Alice", "age": 25}
for key in data.keys():
print(key, data[key])
Instead, use .items()
to get both the key and value at the same time:
for key, value in data.items():
print(key, value) # More readable and efficient!
Why Use .items()
?
- More readable
- More efficient (avoids extra dictionary lookups)
- The Pythonic way
Video Walkthrough
Wrapping Up
Loops are essential in Python, but small mistakes can lead to big problems. Avoiding these errors will make your code:
- Cleaner
- Faster
- Easier to debug
If you found this helpful, share it with a fellow Python coder! And let me know in the comments—what’s the biggest loop mistake you’ve made?