Anti-Patterns in Python Programming
pythonanti-patternscode-qualitybest-practicespythonic
Abstraction: Common Python beginner mistakes and idiomatic alternatives
Key points:
- Avoid range() for simple sequence iteration; use the for-in construct directly; off-by-one bugs are common with range(len(x))
- Prefer list comprehensions over loop-plus-append; can handle nesting and conditionals inline
- Use sets (not lists) for repeated membership testing: set lookup is O(1) vs O(n) for lists; build the set once outside the loop
- Loop variables leak into the enclosing scope in Python (unlike Java); initialize sentinel variables (preferably None) before loops to avoid NameError on empty sequences
- Keep outer scope (global namespace) to IN_ALL_CAPS constants; delegate everything else to functions to avoid accidental global variable capture
- Use
is(not==) when testing for None; follow PEP 8; test empty containers with plainif x:notlen(x) > 0
Connections: Python · Python Best Practices · Code Quality · Software Engineering