What are iterators and generators? What is their purpose?
sobes.tech AI
Answer from AI
Iterators in Python are objects that implement the __next__() method, which returns the next element in the sequence, and the __iter__() method, which returns the iterator itself. They allow sequential traversal of collection elements without the need to load them all into memory at once.
Generators are a convenient way to create iterators using functions that utilize the yield keyword. When a generator function is called, it returns a generator object that resumes execution from the last yield each time next() is called, returning the next value.
The essence of iterators and generators is efficient and lazy (deferred) retrieval of sequence elements, which saves memory and allows working with potentially infinite or very large data sets.
Example of a generator:
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
for number in count_up_to(5):
print(number)
This code will output numbers from 1 to 5 without creating the entire list in memory at once.