Python

Python Generators and Iterators

📅 December 05, 2025 ⏱️ 1 min read 👁️ 5 views 🏷️ Python

Generators provide memory-efficient iteration.

# Generator function
def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)

# Generator expression
squares = (x**2 for x in range(1000000))
print(next(squares))  # 0
print(next(squares))  # 1
🏷️ Tags:
python generators iterators advanced

📚 Related Articles