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.
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:
A generator is a function that yields values one by one using the yield keyword.
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):
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 for loops.
iter() converts iterable objects into iterators.
next() fetches the next value from an iterator.
yield in 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 for loops directly.
Take quizzes related to this topic and see where you stand!
Start Quiz Now