01 / 20

Refactoring in
Python

Learn to transform messy code into clean, readable modules using helper functions and comprehensions.

Python

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.

Readability
Others (and future you) can understand the code faster
Reusability
Extract logic so it can be called from multiple places
Testability
Smaller pieces are easier to test and debug

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.

Helper Functions
Extract repeated or complex logic into a named function. Each function does one thing well.
Comprehensions
Replace verbose for-loop + append patterns with concise one-line expressions for lists, dicts, and sets.

Why Refactoring Matters

BEFORE result = [] for item in data: temp = item * 2 if temp > 10: result.append(temp) # 5 lines, nested logic # mixed responsibilities # hard to reuse Complexity: High AFTER def double(x): return x * 2 result = [ double(i) for i in data if double(i) > 10 ] Complexity: Low

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.

1
Single Responsibility: Each helper does exactly one thing: validate, transform, format, or compute.
2
Descriptive Name: The function name replaces a comment. is_valid_email() is better than # check email.
3
Pure When Possible: Same inputs always produce same outputs. No hidden side effects.

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.

# General form of a list comprehension: [expression for item in iterable if condition]
List
[x**2 for x in range(5)]
Dict
{k: v for k, v in pairs}
Set
{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

1
Identify repetition: Look for duplicated code blocks or copy-pasted logic across your program.
2
Name the responsibility: Give the repeated logic a clear verb-noun name (e.g., calculate_tax, format_name).
3
Extract the helper: Move the logic into a def block. Pass inputs as parameters, return outputs.
4
Replace loop patterns: If the remaining code is init-loop-append, convert to a comprehension.
5
Test: Run the code and verify the output is identical to the original. Refactoring must not change behavior.

Example 1: Extract a Helper

✕ Before: Repeated logic
# Calculate area for each room kitchen = 3.5 * 4.2 * 1.08 # with 8% tax bedroom = 4.0 * 5.0 * 1.08 bath = 2.5 * 3.0 * 1.08
↓
✓ After: Helper function
def taxed_area(length, width, tax=0.08): return length * width * (1 + tax) kitchen = taxed_area(3.5, 4.2) bedroom = taxed_area(4.0, 5.0) bath = taxed_area(2.5, 3.0)

Example 2: Loop to Comprehension

✕ Before: init-loop-append
scores = [85, 42, 91, 67, 73, 55] passing = [] for s in scores: if s >= 70: passing.append(s)
↓
✓ After: List comprehension
scores = [85, 42, 91, 67, 73, 55] passing = [s for s in scores if s >= 70]

Example 3: Combined Refactor

✕ Before: Complex nested loop
emails = ["Bob@X.com", "invalid", "a@b.co"] clean = [] for e in emails: if "@" in e and "." in e: clean.append(e.strip().lower())
↓
✓ After: Helper + comprehension
def is_valid(email): return "@" in email and "." in email def normalize(email): return email.strip().lower() clean = [normalize(e) for e in emails if is_valid(e)]

Decision Flowchart

See repeated / long code? Is it a loop + append? YES Use a comprehension NO Complex or reused logic? YES Extract a helper func NO Leave as is

Dict Comprehension in Action

Dict comprehensions follow the same pattern as list comprehensions but produce key-value pairs.

✕ Before
word_lengths = {} for word in words: word_lengths[word] = len(word)
↓
✓ After
word_lengths = {w: len(w) for w in words}

When Comprehensions Go Too Far

Comprehensions can hurt readability when they become deeply nested or overly complex. Know the line of diminishing returns.

✕ Too complex: nested double comprehension
result = [f(x,y) for x in a if g(x) for y in h(x) if k(y)]
↓
✓ Better: helper + simple comprehension
def valid_pairs(a): pairs = [] for x in a: if g(x): for y in h(x): if k(y): pairs.append((x, y)) return pairs result = [f(x, y) for x, y in valid_pairs(a)]

Common Mistakes

✕ Changing Behavior
Refactoring must preserve output. Always test before and after. If results differ, the refactor is wrong.
✕ Over-Abstracting
Creating a helper for a single line used once adds complexity, not clarity. Only extract when there is real benefit.
✕ Mega-Comprehensions
Cramming triple-nested logic into one comprehension is worse than the original loop. Keep comprehensions simple.

Question 1 of 5

Which is the correct list comprehension refactor of the code above?

Question 2 of 5

What is the primary goal of refactoring code?

Question 3 of 5

Which statement best describes why Code A is a better refactoring choice than Code B?

Question 4 of 5

Which dict comprehension correctly replaces this code?

Question 5 of 5

This comprehension is hard to read. What is the best refactoring strategy?