Convert Data in Python with Comprehensions and Generators

Convert mixed data to integers, filter and transform numbers, and extract fields from dicts using list comprehensions and generator expressions.

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

Python code

31 lines
Python 3.9+
def convert_numbers(data):
    """Convert a list of mixed values into integers using a comprehension."""
    return [int(item) for item in data if item is not None]


def double_even_numbers(numbers):
    """Double only even numbers using a generator expression."""
    return (n * 2 for n in numbers if n % 2 == 0)


def extract_names(people):
    """Extract names from list of dicts with a comprehension."""
    return [person["name"] for person in people if person.get("active")]


if __name__ == "__main__":
    raw_data = ["10", "20", None, "30", "abc"]
    valid_numbers = convert_numbers(raw_data)
    print("Integers:", valid_numbers)

    nums = [1, 2, 3, 4, 5, 6]
    doubled = double_even_numbers(nums)
    print("Doubled evens:", list(doubled))

    users = [
        {"name": "Alice", "active": True},
        {"name": "Bob", "active": False},
        {"name": "Charlie", "active": True},
    ]
    active_names = extract_names(users)
    print("Active names:", active_names)

Output

stdout
Integers: [10, 20, 30]
Doubled evens: [4, 8, 12]
Active names: ['Alice', 'Charlie']

How it works

List comprehensions build a new list by applying an expression to each item that passes a condition, making them ideal for filtering and transformation in one line. Generator expressions use parentheses instead of brackets and produce values lazily, so they consume less memory for large sequences. The is not None check safely skips None values, while person.get('active') returns a boolean safely for missing keys. Using comprehensions keeps code concise and readable without sacrificing clarity.

Common mistakes

  • Treating generator expressions as lists — they are one-time iterables.
  • Forgetting that int('abc') raises ValueError, so data must be pre-filtered.
  • Using square brackets for a generator expression, which creates a list instead.

Variations

  1. Use filter() and map() for a functional approach: list(map(int, filter(None, data)))
  2. Use a generator expression inside sum() or max() to avoid building an intermediate list.

Real-world use cases

  • Cleaning user-provided form inputs by converting numeric strings to integers while ignoring empty fields.
  • Processing API response lists to extract only active records and transform their fields for storage.
  • Streaming large log files and transforming lines with a generator to keep memory usage low.

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.