This Python code looks normal.
It works.
It passes the tests.
But it does extra work dozens, and sometimes hundreds of times.
The most common reason is that you accidentally turn a linear algorithm into a quadratic one.
A typical scenario:
- there's a list
- inside the loop, you repeatedly do in, count, index
- everything works quickly with small data
- on real data, the application starts to "slow down for no reason"
The problem is that:
- list is O(n) for searching
- searching inside the loop = O(n²)
- Python honestly does the work you asked it to do
Pros don't think about "whether it works or not", but how many extra operations are being performed.
The correct approach:
- if you need membership checks, use set
- if you're counting elements, use dict or Counter
- if the data doesn't change, pre-calculate it once
This technique is one of the most common sources of hidden performance bugs in Python code.
# ❌ Bad: O(n²)
users = ["alice", "bob", "carol", "dave"]
for u in users:
if u in users: # full list traversal every time
process(u)
# ✅ Good: O(n)
users = ["alice", "bob", "carol", "dave"]
users_set = set(users)
for u in users:
if u in users_set:
process(u)