Iterators and Generators
⏱ Estimated reading time: 2 min
Iterators and Generators in Python
Python provides iterators and generators to efficiently handle sequences and large data streams. They allow lazy evaluation, meaning values are computed only when needed, saving memory.
1. Iterators
-
An iterator is an object that can be iterated over (looped through).
-
It implements the methods
__iter__()and__next__().
Creating an iterator:
Using iterator in a loop:
Custom iterator class:
2. Generators
-
A generator is a function that yields values one by one using the
yieldkeyword. -
They are memory-efficient because they generate values on demand.
Basic generator example:
Using generators in a loop:
Generator with a sequence (lazy evaluation):
Generator expressions (like list comprehensions but lazy):
3. Advantages of Iterators and Generators
-
Memory efficient: No need to store the entire sequence.
-
Lazy evaluation: Values are computed only when required.
-
Infinite sequences: Can generate sequences without storing them.
-
Simpler code: Cleaner syntax for iteration using
forloops.
4. Practical Example: Fibonacci Sequence Generator
Key Points
-
iter()converts iterable objects into iterators. -
next()fetches the next value from an iterator. -
yieldin a generator function pauses the function and returns a value. -
Generators are ideal for large data streams or infinite sequences.
-
Both iterators and generators support
forloops directly.
Register Now
Share this Post
← Back to Tutorials