Python February 11, 2025 1 min read

Mastering Python Generators

Learn how to use generators for memory-efficient iteration.

L
Layla Mahmoud
Frontend developer and UI/UX specialist
361 views

Table of Contents

  • Loading table of contents...

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. #}

Related Articles

Discussion 0

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

Leave a Comment