Avoid Common Python Pitfalls: From Misusing range to Cleaner List Comprehensions
This article gathers subtle yet frequent Python anti‑patterns—misusing range, improper list comprehensions, performance traps, variable leakage, global‑scope misuse, and PEP8 violations—explaining why they occur, their drawbacks, and offering clear, Pythonic alternatives to write more readable and bug‑free code.
Misusing range
Beginners often use range for simple iteration, assuming it safely handles sequence indices. However, range is not meant for direct sequence iteration; off‑by‑one errors are common because the generated object includes the start value but excludes the end value.
Typical justifications for using range include needing an index, iterating two sequences with the same index, or iterating a slice. These can be replaced respectively with direct element iteration, zip, and slice iteration (with a comment explaining the intent). For large sequences, slicing incurs overhead; in such cases consider xrange (Python 2) or generator‑based approaches.
Proper List Comprehensions
When a loop merely builds a list, replace it with a list comprehension for cleaner, more concise code. Nested loops and conditional logic can also be expressed inside a comprehension, though readability should be considered.
Exceptions where comprehensions are unsuitable include the need for exception handling inside the loop; in those cases, use a regular loop or a helper function.
Performance Pitfalls
Repeated membership checks in list are O(n); using a set (or dict for key‑value pairs) reduces lookup to O(1). Create the set once before the loop to amortize the linear‑time construction cost.
Variable Leakage
Python’s variable scope is broader than many languages expect. A variable referenced inside a function that isn’t found locally is looked up in the enclosing (global) scope, which can mask bugs. Using a sentinel value (commonly None) before the loop helps detect when a loop never executes.
Global Scope Best Practices
Avoid placing mutable or ambiguous variables in the module’s top‑level scope. Use ALL_CAPS for true constants, keep function parameters local, and only use global when you intentionally need to modify a global variable.
PEP 8 and Code Style
Follow the PEP 8 style guide: use proper indentation, blank lines, and naming conventions. Test container emptiness directly (e.g., if my_list:) instead of comparing lengths to zero. Use bool(x) when you need an explicit Boolean result.
When checking for None, use identity comparison ( is None) rather than truthiness checks to distinguish it from other falsy values like 0 or empty containers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
