Chapter 10: Advanced Topics / Lesson 57

Generators

Introduction to Generators

Generators are a special type of function that return an iterator. Instead of returning a value with return, generators use yield to produce values one at a time. This makes generators memory-efficient for large datasets.

Generators are useful when you need to process large amounts of data without loading everything into memory at once.

Creating Generators

Use the yield keyword to create a generator function:

generator_basic.py
# Generator function def countdown(n): while n > 0: yield n n -= 1 # Use the generator for num in countdown(5): print(num) # 5, 4, 3, 2, 1 # Generator for even numbers def evens(limit): n = 0 while n < limit: yield n n += 2 for even in evens(10): print(even) # 0, 2, 4, 6, 8

Generator Expressions

You can create generators using generator expressions (similar to list comprehensions):

generator_expression.py
# Generator expression squares = (x ** 2 for x in range(5)) print(list(squares)) # [0, 1, 4, 9, 16] # Memory efficient - doesn't store all values large_gen = (x * 2 for x in range(1000000)) # Only processes values as needed # Generator with condition evens_gen = (x for x in range(10) if x % 2 == 0) print(list(evens_gen)) # [0, 2, 4, 6, 8]

Benefits of Generators

Generators offer several advantages:

  • Memory efficient - values generated on demand
  • Lazy evaluation - only computes when needed
  • Can represent infinite sequences
  • Cleaner code for iteration patterns
  • Better performance for large datasets

Best Practices

✅ Generator Tips

• Use generators for large datasets or infinite sequences

• Generators can only be iterated once

• Use generator expressions for simple transformations

• Generators are memory-efficient but not faster than lists

• Combine generators with other iterators for powerful data processing

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...