Skip to content

Mastering Python Generators

Learn how to use generators for memory-efficient iteration.

Python Generators

Generators provide lazy evaluation for memory efficiency.

Creating Generators

# Generator function
def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

# Usage
for num in count_up_to(5):
    print(num)

# Generator expression
squares = (x**2 for x in range(1000000))

Benefits

  • Memory efficient for large datasets
  • Lazy evaluation
  • Infinite sequences
{# Provenance for articles generated from a source document. Rendered here rather than stored in the body so it stays accurate and cannot be edited away, and so the sealed draft stays purely generated. #}

Discussion

0

No comments yet. Be the first to start the discussion!

Leave a Comment

Comments are reviewed before they appear.

Write a comment