How to Use List Comprehensions and Generators to Format Data in Python

A beginner-friendly helper that formats dictionaries into strings using a list comprehension and generates squared numbers lazily with a generator.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 13 views 0 copies

Python code

32 lines
Python 3.9+
def format_data(items):
    """Format a list of dictionaries into readable strings."""
    formatted = [
        f"{item.get('name', 'Unknown')}: {item.get('value', 0)} units"
        for item in items
        if item.get('value', 0) > 0
    ]
    return formatted if formatted else ["No positive values found"]


def generate_numbers(start=1, end=10):
    """Generate squared numbers as a generator."""
    for num in range(start, end + 1):
        yield num * num


if __name__ == "__main__":
    sample_data = [
        {"name": "Apples", "value": 5},
        {"name": "Oranges", "value": 0},
        {"name": "Bananas", "value": 3},
        {"name": "Grapes", "value": -2},
        {"name": "Cherries", "value": 8},
    ]

    print("Formatted data:")
    for line in format_data(sample_data):
        print(f"  {line}")

    print("\nSquared numbers (1 to 5):")
    squared_gen = generate_numbers(1, 5)
    print(f"  {list(squared_gen)}")

Output

stdout
Formatted data:
  Apples: 5 units
  Bananas: 3 units
  Cherries: 8 units

Squared numbers (1 to 5):
  [1, 4, 9, 16, 25]

How it works

The format_data function uses a list comprehension to iterate over dictionaries, safely access values with .get(), and filter out non-positive entries in a single readable expression. The generator generate_numbers uses yield to produce squared values one at a time, saving memory for large ranges. A generator becomes exhausted after iteration, which is why converting to a list inside the print statement works cleanly here. Both patterns keep the code concise while remaining easy to read for beginners.

Common mistakes

  • Trying to reuse a generator after it's been consumed—it yields nothing on the second loop.
  • Forgetting that `yield` makes a function a generator; calling it does not run the body immediately.
  • Using `item['name']` directly instead of `.get()` causes a KeyError when a key is missing.

Variations

  1. Write the comprehension as a generator expression like `(f"{...}" for item in items)` to avoid building a full list.
  2. Combine the output into one string with `'\n'.join(format_data(items))` for direct printing.

Real-world use cases

  • Formatting API-driven inventory reports where lines with zero or negative stock are skipped.
  • Generating lazy sequences of computed metrics (like squares, cubes, or rates) for large datasets.
  • Transforming config entries into human-readable log lines while filtering invalid records.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.