Middle
What are generators and why are they needed?
sobes.tech AI
Answer from AI
Generators in Python are functions that return an iterator and allow values to be yielded step-by-step using the yield keyword. They are useful for efficiently working with large amounts of data or infinite sequences, as they do not require loading all data into memory.
Example of a generator that yields squares of numbers from 0 to n-1:
def squares(n):
for i in range(n):
yield i * i
for sq in squares(5):
print(sq)
Output:
0
1
4
9
16
Generators enable lazy evaluation, saving resources and simplifying code.