Refactoring in
Python
Learn to transform messy code into clean, readable modules using helper functions and comprehensions.
What is Refactoring?
Refactoring is the process of restructuring existing code without changing its external behavior. The goal: make code easier to read, easier to maintain, and less prone to bugs.
Two Key Refactoring Tools
Python gives us two powerful patterns for cleaning up code. Master these and you will dramatically improve every program you write.
Why Refactoring Matters
The Helper Function Rule
A helper function is a small, focused function extracted from a larger block of code. It encapsulates a single responsibility and can be called wherever that logic is needed.
is_valid_email() is better than # check email.The Comprehension Rule
A comprehension is a concise syntax for building a new list, dict, or set from an iterable. It replaces the common initialize-loop-append pattern.
[x**2 for x in range(5)]{k: v for k, v in pairs}{x % 3 for x in nums}Helper vs. Comprehension
These tools solve different problems. Know when to reach for each one.
| Helper Function | Comprehension | |
|---|---|---|
| Purpose | Name and isolate logic | Build collections concisely |
| Best for | Complex or reused logic | Simple map/filter patterns |
| Readability | Names replace comments | Removes boilerplate loops |
| Nesting | Reduces nesting depth | Can increase nesting if overused |
| Combo | Use helpers inside comprehensions for best results | |
How to Refactor Step by Step
calculate_tax, format_name).def block. Pass inputs as parameters, return outputs.Example 1: Extract a Helper
Example 2: Loop to Comprehension
Example 3: Combined Refactor
Decision Flowchart
Dict Comprehension in Action
Dict comprehensions follow the same pattern as list comprehensions but produce key-value pairs.
When Comprehensions Go Too Far
Comprehensions can hurt readability when they become deeply nested or overly complex. Know the line of diminishing returns.
Common Mistakes
Question 1 of 5
Original code:
result = []
for n in numbers:
if n % 2 == 0:
result.append(n ** 2)
Which is the correct list comprehension refactor of the code above?
n ** 2) and the filter (if n % 2 == 0). Option (a) misses the squaring, (c) reverses the logic, and (d) produces a set, not a list.Question 2 of 5
What is the primary goal of refactoring code?
Question 3 of 5
Code A:
def calc(x, y): return x * y * 1.08
Code B:
a = 3 * 4 * 1.08
b = 5 * 6 * 1.08
c = 7 * 8 * 1.08
Which statement best describes why Code A is a better refactoring choice than Code B?
calc centralizes the formula with the tax rate 1.08. If the rate changes, you update one line instead of three. This is the core benefit of extracting a helper: single source of truth.Question 4 of 5
Code:
names = ["Alice", "Bob", "Charlie"]
lengths = {}
for name in names:
lengths[name] = len(name)
Which dict comprehension correctly replaces this code?
key: value pair. Option (a) uses square brackets (list syntax). Option (b) produces a set of integers. Option (c) produces a set of names. Only (d) creates the correct dictionary mapping.Question 5 of 5
Code:
result = [f(x, y) for x in a if g(x) for y in h(x) if k(y)]
This comprehension is hard to read. What is the best refactoring strategy?
for clauses and conditions, the best approach is to extract a helper function that encapsulates the complex iteration, then use a simple comprehension that calls the helper. Comments alone do not fix structural complexity.