Reference library

Comprehensions & generators

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

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

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

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.