Junior — Middle
Have you had experience using generators in your projects?
sobes.tech AI
Answer from AI
Yes, generators in Python are a convenient way to create iterators using a function that uses the yield keyword. They save memory because values are generated one at a time as needed, rather than creating the entire list at once.
Example of a generator that returns numbers from 1 to n:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)
Generators are useful when working with large data, streams, or when lazy evaluation of a sequence is needed.