Module 11: Python Advanced ConceptsBeginner18 min read
Generators & The Yield Keyword
Memory-efficient lazy sequence evaluation with generator functions.
Key Takeaways & Core Concepts
- Memory Efficient: Generating a sequence of 10,000,000 items in a list consumes gigabytes of RAM. A generator produces elements on demand with minimal memory footprint.
- Lazy Evaluation: Computation only happens when requested via
next()or in aforloop.
Generators & The Yield Keyword
### Python Generators
Generators are functions that return an iterator that yields one item at a time using the yield keyword, instead of returning an entire list in memory.
#### Why Use Generators?
- Memory Efficient: Generating a sequence of 10,000,000 items in a list consumes gigabytes of RAM. A generator produces elements on demand with minimal memory footprint.
- Lazy Evaluation: Computation only happens when requested via
next()or in aforloop.
PYTHON Code Example
1def count_up_to(max_val):
2 count = 1
3 while count <= max_val:
4 yield count
5 count += 1
6
7counter = count_up_to(3)
8print(next(counter)) # 1
9print(next(counter)) # 2
10print(next(counter)) # 3
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
10 lines
Fibonacci Generator
1def fibonacci(limit):
2 a, b = 0, 1
3 count = 0
4 while count < limit:
5 yield a
6 a, b = b, a + b
7 count += 1
8
9fib_numbers = list(fibonacci(7))
10print("Fibonacci:", fib_numbers)
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
10 lines
Note: The generator maintains its execution state across successive yield calls.
Practice & AssessmentPython Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)