10.17 Best Practices
Preferring a list comprehension over a manual loop when it stays readable, choosing append() over insert(0, ...), converting to a set for repeated membership checks, and picking the right collection type for the job.
Readable Code
Prefer a list comprehension over an equivalent manual for + .append() loop when it stays short and clear — but fall back to a full loop once the logic gets complex enough that the comprehension becomes hard to read. See 10.9 Traversing and List Comprehensions.
Efficient Methods
Use append() over insert(0, ...) when order allows, and convert to a set for repeated membership testing on large collections. See 10.13 Performance.
Choose the Right Structure
Not every ordered collection should be a list — reach for tuple when the contents are fixed, set when uniqueness matters more than order, and dict when items need to be looked up by a key rather than a position. See 5.4 Sequence Data Types and 5.9 Mutable vs Immutable Types.
Quick Interview Answer
“Three habits cover most of what matters: prefer a comprehension over a manual
append()loop while it stays readable, but don’t force a genuinely complex transformation into one just to be terse; default toappend()overinsert(0, ...)and reach for asetwhen membership is checked repeatedly, since both are about respecting the actual time complexity of list operations; and don’t reflexively reach for a list at all — atuplefor fixed data, asetfor uniqueness, or adictfor key-based lookup is often the structurally correct choice.”
Common Mistakes
- Forcing a multi-condition, multi-step transformation into a single comprehension purely for brevity, producing something harder to read than the equivalent explicit loop.
- Defaulting to a list for data that’s never going to change, when a
tupledocuments that intent and is slightly more memory-efficient. - Using a list for a large collection that’s checked for membership repeatedly, instead of a
set, and paying an unnecessary O(n) cost on every check.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form