Junior — Middle
What is the main role and purpose of generators in Python?
sobes.tech AI
Answer from AI
Generators in Python are used to create iterators with a function that returns values one at a time, pausing its execution between calls. This allows efficient handling of large data volumes without loading the entire sequence into memory at once.
The main purpose of generators is lazy evaluation of sequence elements, which saves memory and can improve performance when processing data streams or large collections.
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)
Here, yield returns a value and saves the function's state for the next call.