Junior — Middle
Can you give an example of using a generator that helps reduce memory consumption?
sobes.tech AI
Answer from AI
Generators in Python allow iterating over a sequence of data without loading the entire sequence into memory at once. This is especially useful when working with large volumes of data.
Example: instead of creating a list of millions of numbers, you can use a generator that yields numbers one by one:
# Generator that returns squares of numbers from 0 to n-1
def squares(n):
for i in range(n):
yield i * i
# Using the generator
for square in squares(10**6):
# Process each square one by one
pass
Thus, memory is used only for the current value, not for the entire list at once.