Reference library

Comprehensions & generators

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

12 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

Count Data in Python with Comprehensions and Generators

Count list items with a dict comprehension and generate squares lazily with a generator expression, printing both results.

comprehensions generators counter
Python
from collections import Counter

data = ["apple", "banana", "apple", "cherry", "banana", "apple"]

counts = {item: data.count(item) for item in set(data)}

square_gen = (x * x for x in range(5))
squares = list(square_gen)

if __name__ == "__main__":
    print("Manual count:", counts)
    print("Counter:", dict(Counter…
15 0 Open
Comprehensions & generators easy

Generate Data with Python Comprehensions and Generators

Shows list, dict compregensions and generator expressions plus a Fibonacci generator to produce data lazily.

comprehensions generators lazy-evaluation
Python
# Data generation helpers using comprehensions and generators
from itertools import islice


def fibonacci(limit):
    """Generate Fibonacci numbers up to a limit."""
    a, b = 0, 1
    while a <= limit:
        yield a
        a, b = b, a + b


def main():
    # List comprehension: squares of even numbers
    square…
15 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 Split Data into Chunks and Use Generators in Python

Split a list into fixed-size chunks with a list comprehension and square even numbers lazily with a generator expression.

comprehensions generators chunking
Python
def split_numbers(data, chunk_size):
    return [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]


def square_even_numbers(numbers):
    return (n ** 2 for n in numbers if n % 2 == 0)


if __name__ == "__main__":
    sample_data = list(range(1, 21))
    chunks = split_numbers(sample_data, 5)
    print…
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 List Comprehensions and Generators in Python

Analyze a list of numbers using a list comprehension to square evens, a generator for sum, and a generator expression for the maximum squared value.

comprehensions generators list-comprehension
Python
def analyze_numbers(numbers):
    squared = [n ** 2 for n in numbers if n % 2 == 0]
    total = sum(n for n in numbers)
    max_squared = max((n ** 2 for n in numbers), default=0)
    return squared, total, max_squared


if __name__ == "__main__":
    data = [1, 2, 3, 4, 5, 6]
    evens_squared, total_sum, max_sq = an…
11 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
Comprehensions & generators easy

Normalize Data in Python with Comprehensions and Generators

Clean a list by dropping None values with a comprehension, then min-max normalize it using a lazy generator expression — a beginner-friendly data preparation pattern.

comprehensions generators normalization
Python
import statistics

# Sample raw data including missing and outlier-ish values
raw = [22, 18, None, 25, 30, 19, 22, 17, None, 28, 24]

# Clean the data: drop None values using a list comprehension
clean = [x for x in raw if x is not None]

# Normalize using min-max scaling with a generator expression
min_val = min(clea…
13 0 Open
Comprehensions & generators easy

Python Comprehensions and Generators for Beginners

Learn list, dict, and set comprehensions plus generator expressions and generator functions with clear, runnable examples.

comprehensions generators lazy-evaluation
Python
# Demonstrates list comprehensions, dict comprehensions, set comprehensions, and generators

def demonstrate_comprehensions():
    # List comprehension: squares of even numbers
    numbers = range(1, 11)
    even_squares = [n ** 2 for n in numbers if n % 2 == 0]
    
    # Dict comprehension: number to its factorial
 …
15 0 Open
Comprehensions & generators easy

Sum of Squares with a Generator Expression in Python

This code computes the sum of squares of integers from 1 to n using a generator expression, demonstrating a memory-efficient and concise way to aggregate a sequence.

generator sum squares
Python
def sum_of_squares(n):
    return sum(x * x for x in range(1, n + 1))

if __name__ == "__main__":
    print(f"Sum of squares from 1 to 5: {sum_of_squares(5)}")
    print(f"Sum of squares from 1 to 10: {sum_of_squares(10)}")
14 0 Open
Comprehensions & generators easy

Write Data Helpers with Comprehensions and Generators in Python

Demonstrates list, dict, and set comprehensions plus generator expressions and generator functions for building concise data helpers.

comprehensions generators data-helpers
Python
# Basic comprehensions and generators demo

# List comprehension: squares of evens
squares = [x * x for x in range(10) if x % 2 == 0]
print("List comp:", squares)

# Dictionary comprehension: char -> count
text = "hello"
char_counts = {c: text.count(c) for c in set(text)}
print("Dict comp:", char_counts)

# Set compre…
10 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.