Reference library

Comprehensions & generators

List/dict/set comprehensions, generator expressions, and lazy iteration.

10 matches
Comprehensions & generators easy

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.

comprehensions generators list-comprehension
Python
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)


d…
15 0 Open
Comprehensions & generators easy

How to Filter Data with Predicates in Python

This helper filters a list with a predicate using a list comprehension, plus a lazy generator version that yields matches one by one.

filtering comprehensions generators
Python
def filter_data(data, predicate):
    """Return a list containing only items that pass the predicate."""
    return [item for item in data if predicate(item)]


def filter_data_lazy(data, predicate):
    """Generator version: yields items that pass the predicate one by one."""
    for item in data:
        if predicat…
16 0 Open
Comprehensions & generators easy

How to Parse Data with Generators and Comprehensions in Python

This code demonstrates using a generator expression to filter active users and a dictionary comprehension to aggregate scores by name.

generator expressions dictionary comprehensions filtering
Python
def parse_data_helper(raw_records):
    """Extract active users' names and scores from raw records."""
    parsed = (
        (record["name"], record["score"])
        for record in raw_records
        if record["active"] and record["score"] >= 0
    )
    return list(parsed)


def aggregate_scores(parsed_data):
    "…
15 0 Open
Comprehensions & generators easy

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.

list comprehension generators formatting
Python
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 g…
13 0 Open
Comprehensions & generators easy

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

Transform a list of integers by squaring even numbers with a list comprehension and cubing odd numbers with a generator.

comprehensions generators list-comprehension
Python
def transform_data(data):
    """
    Transform a list of integers:
    - squares of even numbers using a list comprehension
    - cubes of odd numbers using a generator
    """
    squares = [num ** 2 for num in data if num % 2 == 0]
    cubes = (num ** 3 for num in data if num % 2 != 0)
    return squares, cubes


i…
15 0 Open
Comprehensions & generators easy

How to Validate Data with Python Comprehensions and Generators

Use list, generator, and dictionary comprehensions to filter and transform data for quick validation in Python.

comprehensions generators validation
Python
def validate_integer(data):
    return [item for item in data if isinstance(item, int)]

def validate_positive(numbers):
    return (num for num in numbers if num > 0)

def validate_string_lengths(data, min_length=3):
    return {item: len(item) for item in data if isinstance(item, str) and len(item) >= min_length}

i…
14 0 Open
Comprehensions & generators easy

How to filter even numbers with a Python list comprehension

Build a new list of only the even numbers from 1 to 20 using a single list comprehension with a filter condition.

list comprehension even numbers filtering
Python
even_numbers = [num for num in range(1, 21) if num % 2 == 0]
print(even_numbers)
12 0 Open
Comprehensions & generators easy

How to skip items until a condition is met in Python

Use itertools.dropwhile to skip leading elements while a predicate returns true, then yield the rest of the sequence unchanged.

itertools generators dropwhile
Python
def is_negative(x):
    return x < 0

numbers = [-3, -1, 0, 5, 2, -8, 7]
result = list(itertools.dropwhile(is_negative, numbers))
print(f"Original: {numbers}")
print(f"After dropwhile: {result}")
13 0 Open
Comprehensions & generators easy

List Comprehension to Filter Even Numbers in Python

Creates a new list containing only the even numbers from an existing list using a list comprehension with a condition.

list comprehension filtering even numbers
Python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [n for n in numbers if n % 2 == 0]
print(f"Original: {numbers}")
print(f"Even numbers: {even_numbers}")
13 0 Open
Comprehensions & generators easy

Merge Data with Comprehension and Generator in Python

Merge user and order data using a dictionary comprehension for lookups and a generator expression to filter and transform orders.

dictionary-comprehension generator-expression data-merging
Python
def merge_data(users, orders):
    """
    Merge user and order data using a dictionary comprehension
    and a generator expression for filtering.
    """
    # Build a lookup: user_id -> user name
    user_map = {user["id"]: user["name"] for user in users}

    # Generator: yield orders with user names attached
    …
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Comprehensions & generators — Python code examples

What you will find here

This page collects comprehensions & generators snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.