Reference library

Comprehensions & generators

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

60 matches
Comprehensions & generators easy

How to Generate Combinations with Replacement in Python

Generate all r-length combinations with repetition from a list using the standard library itertools.combinations_with_replacement function.

itertools combinations generator
Python
from itertools import combinations_with_replacement

items = ['A', 'B', 'C']
r = 2

combos = list(combinations_with_replacement(items, r))

for combo in combos:
    print(combo)

if __name__ == "__main__":
    print(f"Total combinations with replacement: {len(combos)}")
11 0 Open
Comprehensions & generators easy

How to Generate Fibonacci Numbers in Python Without Recursion

Build an efficient infinite Fibonacci sequence using a generator function with O(1) memory and no recursion overhead.

generators fibonacci iteration
Python
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

if __name__ == "__main__":
    count = 10
    result = list(fib(count))
    print(result)
15 0 Open
Comprehensions & generators easy

How to Generate Permutations of Length r in Python

Generate all ordered arrangements of length r from a given list of elements using itertools.permutations.

permutations itertools combinatorics
Python
from itertools import permutations

def generate_permutations(elements, r):
    """Generate all r-length permutations of the given elements."""
    return list(permutations(elements, r))

if __name__ == "__main__":
    elements = ['A', 'B', 'C']
    r = 2
    result = generate_permutations(elements, r)
    print(f"Ele…
14 0 Open
Comprehensions & generators easy

How to Generate a Collatz Sequence in Python

Generate the Collatz sequence for a given positive integer by repeatedly applying the 3n+1 rule until reaching 1.

collatz sequence loops
Python
def collatz_sequence(n):
    if n <= 0:
        raise ValueError("n must be a positive integer")
    sequence = [n]
    while n != 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        sequence.append(n)
    return sequence

if __name__ == "__main__":
    start = 7
    result…
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 Implement takewhile Generator in Python

A generator that yields items from an iterable until a condition fails, like itertools.takewhile.

generator takewhile iteration
Python
def takewhile(predicate, iterable):
    for item in iterable:
        if not predicate(item):
            break
        yield item

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5, 1, 2, 3]
    result = list(takewhile(lambda x: x < 4, numbers))
    print(result)
13 0 Open
Comprehensions & generators easy

How to Implement the Iterator Protocol in Python

A manual iterator class using __iter__ and __next__, compared with an equivalent generator using yield.

iterator generator protocol
Python
class ManualCounter:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.limit:
            raise StopIteration
        value = self.current
        self.current += 1
        return valu…
13 0 Open
Comprehensions & generators easy

How to Lazily Transform Items in Python with a Generator

Map a transform function over an iterable lazily with a generator so items are processed on demand, not up front.

generators lazy evaluation mapping
Python
def lazy_map(items, transform):
    for item in items:
        yield transform(item)

def double(x):
    return x * 2

def upper(s):
    return s.upper()

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    doubled = lazy_map(numbers, double)
    print("Doubled numbers:", end=" ")
    for value in doubled:
  …
14 0 Open
Comprehensions & generators easy

How to Merge Multiple Iterables with a Generator in Python

This code defines a generator function that 'chains' or merges multiple iterables into a single iterator, which is then converted to a list.

generators yield-from iterables
Python
def chain(*iterables):
    for iterable in iterables:
        yield from iterable

def main():
    list1 = [1, 2, 3]
    tuple1 = (4, 5)
    set1 = {6, 7}
    string1 = "89"

    result = list(chain(list1, tuple1, set1, string1))
    print(result)

if __name__ == "__main__":
    main()
12 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 Repeat a Generator Cycle Single Value in Python

Build a generator that repeats a single value across multiple cycles, each cycle adding an extra repetition to mark its completion.

generators loops repeat
Python
def repeat_with_cycle(value, cycle_limit, repetitions):
    """
    Repeats a single value until reaching a cycle limit,
    then yields the value one more time to demonstrate a full cycle.
    
    Args:
        value: The single value to repeat.
        cycle_limit: Number of repetitions per cycle.
        repetitio…
13 0 Open
Comprehensions & generators easy

How to Reset Python's Random Seed for Deterministic Output

This code shows how to seed Python's random module to generate identical random sequences across runs, ensuring reproducibility.

random seeding deterministic
Python
import random

def seeded_random_sequence(seed, count=5, low=1, high=100):
    random.seed(seed)
    return [random.randint(low, high) for _ in range(count)]

if __name__ == "__main__":
    seed_value = 42
    first_run = seeded_random_sequence(seed_value)
    print("First run:", first_run)

    # Reset seed and gener…
12 0 Open
Comprehensions & generators easy

How to Slice a Generator with islice in Python

Use itertools.islice to take the first n items from any iterable without materializing the whole sequence into a list.

itertools islice generators
Python
from itertools import islice


def first_n(iterable, n):
    """Return the first n items from an iterable."""
    return list(islice(iterable, n))


if __name__ == "__main__":
    numbers = range(10, 100)  # large iterable
    result = first_n(numbers, 5)
    print(result)  # [10, 11, 12, 13, 14]
14 0 Open
Comprehensions & generators easy

How to Sort Data with Comprehensions and Generators in Python

Sort a list of tuples by a key, then use a list comprehension to extract names and a generator to square high ranks.

sorting list-comprehension generator
Python
data = [("Anna", 3), ("Ben", 1), ("Clara", 2), ("Dan", 5), ("Eve", 4)]

# Comprehension: list of tuples (name, rank) sorted ascending by rank
sorted_by_rank = sorted(data, key=lambda x: x[1])

# Comprehension: extract just the names in rank order
names_in_rank_order = [name for name, rank in sorted_by_rank]

# Generat…
13 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 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 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 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

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.