Why This Matters
Most beginner Python DSA mistakes are not advanced algorithm mistakes. They are small loop and sequence mistakes: off-by-one ranges, clumsy index tracking, accidental copies from slicing, or sorting by the wrong key.
Core Idea
Use the idiom that matches the scan.
| Need | Idiom | Example |
|---|---|---|
| Index and value | enumerate | for i, x in enumerate(values) |
| Pair adjacent values | zip | zip(values, values[1:]) |
| Controlled integer loop | range | range(start, stop, step) |
| Custom ordering | sorted(..., key=...) | sorted(words, key=len) |
| Transform/filter | list comprehension | [x * x for x in values if x > 0] |
| Subsequence | slicing | values[left:right] |
Non-Example or Failure Mode
Slicing is convenient, but it usually creates a new list or string. In tight loops, repeated slicing can turn a linear-looking solution into a quadratic one. Prefer indices for hot paths.
Worked Example
Sort intervals by start, then end:
intervals = [(5, 8), (1, 4), (1, 3)]
ordered = sorted(intervals, key=lambda item: (item[0], item[1]))
The key= function says exactly what comparison matters. That is clearer than writing a custom comparator.
Runnable Drill
Core Python idioms drill
Output will appear here.
Common Mistakes
| Mistake | Correction |
|---|---|
Writing for i in range(len(values)) when only the value is needed. | Loop directly over values. |
| Manually maintaining an index variable. | Use enumerate. |
| Building pairs with fragile index math. | Use zip(values, values[1:]) for adjacent pairs. |
| Repeatedly slicing inside a loop. | Track left and right indices when copy cost matters. |
| Sorting tuples without checking tie-breakers. | Use key= so ordering is explicit. |
Diagnostic Questions
| Question type | Question | Answer signal |
|---|---|---|
| Definition | What does enumerate add? | It pairs each item with its index. |
| Example / non-example | Is slicing free? | No; list and string slices usually allocate a copy. |
| Computation | What does range(0, 5, 2) produce? | 0, 2, 4. |
| Transfer | Why use key= in sorting intervals? | It makes start/end ordering explicit. |
Exercises
Beginner:
- Rewrite an index loop with
enumerate. - Use
zipto compute adjacent differences. - Sort words by length, then alphabetically.
Intermediate:
- Replace repeated substring slicing with index boundaries.
- Write a list comprehension that filters and transforms in one pass.
Challenge:
- Implement merge-intervals using
sorted(..., key=...)and no manual comparator.
References
- Python documentation.
enumerate,zip,range, andsorted: https://docs.python.org/3/library/functions.html - Python documentation. Sequence operations and slicing: https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range
- Python documentation. Sorting HOW TO: https://docs.python.org/3/howto/sorting.html