TGViewer
Learn Python Coding Learn Python Coding @pythonre · 40.8K subscribers
Post #9226 1.13K
⚡️ Python code that works, but does extra work 100 times over

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)
  • ❤ 5
More from @pythonre
  1. Oct 10, 2026📚 Download 10 Python books for FREE: 1. Think Python — O’Reilly https://t.co/X7y3pX68IW 2…
  2. Oct 7, 2026Python Lists: A Quick Reference 🐍 * Definition: Lists are ordered, mutable collections th…
  3. Oct 7, 2026📱 270 tools for Python developers The repository contains: 🫡 Linters and formatters; 🫡…
  4. Oct 7, 2026Hands On Python Data Science - Data Science Bootcamp Master Python for Data Science with R…
  5. Oct 6, 2026Post #9851
  6. Oct 6, 2026Python For Beginners Course In-Depth Python: A Comprehensive Introduction to Fundamental P…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →