Junior — Middle
What is the similarity between generator and iterator mechanisms in Python, and how are they used to traverse collections?
sobes.tech AI
Answer from AI
Generators and iterators in Python are used for sequentially traversing collections or other sequences, but they have some similarities and differences.
Similarities:
- Both allow retrieving elements one by one without loading the entire collection into memory.
- An iterator is an object with a
__next__()method that returns the next element or raisesStopIterationat the end. - A generator is a special type of iterator created using a function with the
yieldkeyword.
Usage:
- Iterators are usually created by calling the
iter()function on a collection. - Generators enable writing more compact and lazy code for creating sequences.
Example of a generator for traversing a collection:
def my_generator(collection):
for item in collection:
yield item
for element in my_generator([1, 2, 3]):
print(element)
Thus, generators are a convenient way to create iterators using functions, and iterators are a more general interface for traversing collections.