Python Programming 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
13 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

Related Articles

Discussion 0

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

Leave a Comment