Transform data without loading everything
Use comprehensions for clarity and streaming for large input.
Choose a readable transformation
A comprehension is useful for a short map-and-filter operation. When the expression needs several branches, error handling, or logging, a loop is often clearer. Keep the result's type in mind: a list comprehension builds the whole list, while a generator expression produces items lazily.
Stream a file
Iterating over a file handle reads lines incrementally. Use a with block so the file closes even if processing raises an exception. Validate each line with its line number, and decide whether a bad row stops the import or is recorded for review.
with open(path, encoding='utf-8') as source:
for line_number, line in enumerate(source, start=1):
process(line_number, line.rstrip('\n'))
Watch hidden accumulation
A streaming parser loses its memory advantage if it appends every result to a list before saving. Process in bounded batches or yield values to the caller. Test with an empty file, a malformed middle line, and a large synthetic file. Measure peak memory if the job is intended for very large input.
Check your understanding
Why can a generator expression still lead to high memory use?
Show explanation
A caller may immediately convert it to a list or accumulate every result. The whole pipeline must remain bounded.
You can read for free. Create an account to save your progress.
Next lesson: Use generators to keep pipelines bounded →Put this lesson into practice
A practice activity at this level in the same module.
Try: Stream a large file without loading itFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.