Reference library

Comprehensions & generators

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

69 matches
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

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 Use starmap() to Unpack Tuple Arguments in Python

Use itertools.starmap to apply a function to each tuple in an iterable, unpacking tuple elements as separate arguments and returning an iterator of results.

itertools starmap generators
Python
from itertools import starmap

def multiply(a, b):
    return a * b

if __name__ == "__main__":
    pairs = [(2, 3), (4, 5), (6, 7), (8, 9)]
    results = list(starmap(multiply, pairs))
    print(results)
14 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 medium

How to filter a generator with a predicate function in Python

This code defines a generator function that yields only items from an iterable that satisfy a given predicate, then tests it with even and positive number filters.

generators filtering lazy evaluation
Python
def filter_gen(predicate, iterable):
    for item in iterable:
        if predicate(item):
            yield item

def is_even(num):
    return num % 2 == 0

def is_positive(num):
    return num > 0

if __name__ == "__main__":
    numbers = range(-5, 10)
    
    even_numbers = list(filter_gen(is_even, numbers))
    p…
10 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 generate combinations in Python with itertools

Generate all unique combinations of r items from a given list using itertools.combinations.

itertools combinations generators
Python
import itertools

def combinations_generator(items, r):
    return list(itertools.combinations(items, r))

if __name__ == "__main__":
    items = ['A', 'B', 'C', 'D']
    r = 2
    result = combinations_generator(items, r)
    for combo in result:
        print(combo)
    print(f"Total: {len(result)} combinations of {…
14 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 medium

How to stream parse JSON arrays in Python

This code demonstrates two generators: one that streams a JSON array as individual chunks, and another that incrementally parses those chunks into Python objects using json.JSONDecoder.

json generator streaming
Python
import json


def json_array_stream(items):
    """Generator that yields JSON-encoded values one at a time."""
    yield "["
    for i, item in enumerate(items):
        if i > 0:
            yield ","
        yield json.dumps(item)
    yield "]"


def parse_json_stream(stream):
    """Consumes a stream of JSON fragme…
14 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

Memory efficient map over large file in Python

A generator-based streaming map that processes a large file line by line without loading the whole file into memory.

generator file-io streaming
Python
import sys

def process_lines(file_path):
    """Memory-efficient map over a large file: yields processed lines."""
    with open(file_path, 'r') as f:
        for line in f:
            # Example mapping: strip whitespace and uppercase
            yield line.strip().upper()

if __name__ == "__main__":
    # Use a sma…
12 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 medium

Merge Sorted Iterators with a Heap Generator in Python

Merge multiple sorted iterators into a single sorted stream using a heap and generator, yielding values lazily in order.

heapq generator merge
Python
import heapq

def merge_sorted_iterators(*iterators):
    heap = []
    for idx, iterator in enumerate(iterators):
        try:
            value = next(iterator)
            heapq.heappush(heap, (value, idx, iterator))
        except StopIteration:
            continue

    while heap:
        value, idx, iterator = …
15 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

Python Generator to Filter Duplicates with a Seen Set

A lazily-evaluated generator function that yields only the first occurrence of each item, using a set to track seen values.

generator dedupe set
Python
def unique_generator(items):
    seen = set()
    for item in items:
        if item not in seen:
            seen.add(item)
            yield item

if __name__ == "__main__":
    data = [1, 2, 2, 3, 3, 3, 4, 5, 5]
    result = list(unique_generator(data))
    print(result)
14 0 Open
Comprehensions & generators easy

Set Comprehension for Unique Word Lengths in Python

Use a set comprehension to extract unique word lengths from a string, then sort and print the result.

set comprehension unique word lengths
Python
text = "hello world hello python programming"

word_lengths = {len(word) for word in text.split()}

print("Unique word lengths:", word_lengths)
print("Sorted:", sorted(word_lengths))
10 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

Take n items from an infinite Python generator

Uses itertools.islice to lazily take exactly n items from an infinite generator without exhausting it.

generators itertools islice
Python
from itertools import islice

def count_up_from(start=0):
    n = start
    while True:
        yield n
        n += 1

def take_n(generator, count):
    return list(islice(generator, count))

if __name__ == "__main__":
    gen = count_up_from(10)
    result = take_n(gen, 5)
    print(result)
11 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.