Python Learning
⚡️ Why Is This Loop So Slow?
Imagine you're checking whether thousands of usernames exist.
for username in usernames:
if username in banned_users:
...
If banned_users is a list, Python checks one element at a time.
Alice?
Bob?
Charlie?
David?
...
For every lookup.
Now imagine banned_users is a set. Python doesn't search one by one. It uses a hash table to jump directly to where the value should be.
That's why changing this:
banned_users = [...]
into this:
banned_users = {...}
can dramatically speed up membership checks without changing the rest of your code.
1 · 640 ·