Reference library

Comprehensions & generators

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

1 match
Comprehensions & generators easy

How to Accumulate Values with a Generator in Python

This generator yields the running total of an iterable's elements, producing a cumulative sum with each step.

generator accumulate cumulative-sum
Python
def accum(iterable):
    total = 0
    for item in iterable:
        total += item
        yield total

# Demo
if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]
    print(list(accum(data)))  # [1, 3, 6, 10, 15]

    # Also works with any iterable, e.g., range
    print(list(accum(range(1, 6))))  # [1, 3, 6, 10, 15]
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.