generator¶
- generators are a powerful and versatile tool for creating iterators.
- They are functions that can return an iterator object.
- Unlike regular functions that return a single value after execution, generators can yield multiple values on demand, one at a time.
- Creating Generators
- Generators are defined using a regular
def
keyword, but with ayield
statement instead of areturn
statement. - The
yield
statement pauses the function's execution and returns a value. - When the generator is called again, it resumes execution from the point where it yielded the last value.
- Generators are defined using a regular
In [ ]:
Copied!
def fibonacci_generator(n):
"""Generates a sequence of Fibonacci numbers up to n."""
a, b = 0, 1
for i in range(n):
yield a
a, b = b, a + b
fibonacci_series = fibonacci_generator(10) # Get an iterator object
# Access elements using next() or for loop
print(next(fibonacci_series)) # Output: 0
print(next(fibonacci_series)) # Output: 1
for number in fibonacci_series:
print(number) # Output: 1, 2, 3, 5, 8, ...
def fibonacci_generator(n):
"""Generates a sequence of Fibonacci numbers up to n."""
a, b = 0, 1
for i in range(n):
yield a
a, b = b, a + b
fibonacci_series = fibonacci_generator(10) # Get an iterator object
# Access elements using next() or for loop
print(next(fibonacci_series)) # Output: 0
print(next(fibonacci_series)) # Output: 1
for number in fibonacci_series:
print(number) # Output: 1, 2, 3, 5, 8, ...
- Explanation
- The
fibonacci_generator
function yields the next Fibonacci number in each iteration using theyield
statement. - Calling
fibonacci_generator(10)
doesn't execute the entire function; it creates an iterator object that remembers its state. next(fibonacci_series)
calls the generator and retrieves the first value (0). Subsequent calls tonext
or using afor
loop continue iterating through the sequence.
- The
- Benefits of Using Generators
- Memory Efficiency: Generators are ideal for working with large datasets or infinite sequences as they don't store all the values in memory at once.
- Lazy Evaluation: Values are generated only when requested, making them suitable for scenarios where you don't need all elements upfront.
- Conciseness: Generator expressions offer a compact way to create iterators without defining a full function.
- Common Use Cases
- Generating large sequences like Fibonacci numbers or prime numbers.
- Processing data in files line by line.
- Creating custom iterators for complex data structures.
- Comparison with Regular Functions
- Regular functions return a single value after execution.
- Generators return an iterator object that yields values one at a time.
- Key Points
- Generators are functions that produce a sequence of values on demand using
yield
. - They are memory-efficient as they generate values only when needed.
- You can iterate over a generator using
next
or afor
loop. - Generators can be used to create custom iterators for various purposes.
- Generators are functions that produce a sequence of values on demand using