Reference library

Comprehensions & generators

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

8 matches
Comprehensions & generators easy

Dict Comprehension to Map Keys to Lengths in Python

Build a dictionary that maps each word to its character count using a dictionary comprehension.

dictionary comprehension len
Python
words = ["apple", "banana", "cherry", "date", "elderberry"]

word_lengths = {word: len(word) for word in words}

print(word_lengths)
14 0 Open
Comprehensions & generators easy

How to Group Data in Python with defaultdict and Comprehensions

Group a list of items by a computed key using a defaultdict-based generator helper and an alternative dictionary comprehension approach.

grouping defaultdict comprehensions
Python
from collections import defaultdict

def group_by(data, key_func):
    """Group items in data by the value returned by key_func."""
    result = defaultdict(list)
    for item in data:
        result[key_func(item)].append(item)
    return dict(result)

def group_by_comprehension(data, key_func):
    """Same grouping …
15 0 Open
Comprehensions & generators easy

How to Parse CSV Rows as Generator Dicts in Python

Reads a CSV file and yields each row as a dictionary one at a time using a generator, so the file is processed lazily.

csv generator parsing
Python
import csv
from pathlib import Path

def csv_to_dicts(filepath):
    with open(filepath, mode="r", newline="", encoding="utf-8") as file:
        reader = csv.DictReader(file)
        for row in reader:
            yield row

if __name__ == "__main__":
    sample_csv = Path("sample_data.csv")
    sample_csv.write_text…
13 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 Comprehensions and Generators in Python

Demonstrate list, set, and dictionary comprehensions plus generator expressions and generator functions in one beginner-friendly script.

comprehensions generators yield
Python
def demonstrate_comprehensions_generators():
    # List comprehension: transform and filter in one line
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    squares = [num ** 2 for num in numbers if num % 2 == 0]
    print(f"Square of even numbers (list comprehension): {squares}")

    # Set comprehension: unique values
…
15 0 Open
Comprehensions & generators easy

How to Use Comprehensions and Generators to Check Data in Python

A beginner-friendly helper that filters numeric values, computes squares and cubes with comprehensions and a generator, and returns a summary dictionary.

comprehensions generators data-checking
Python
def check_data(iterable):
    """Return a summary of numeric data using comprehensions and a generator."""
    values = [item for item in iterable if isinstance(item, (int, float))]
    squares = [x ** 2 for x in values if x > 0]
    cubes = (x ** 3 for x in values if x > 0)
    cube_list = list(cubes)
    return {
  …
13 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

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.