Junior — Middle
Explain the working principle of generators in Python and their main advantages
sobes.tech AI
Answer from AI
Generators in Python are functions that return an iterator and allow sequential generation of values using the yield keyword. Instead of returning all values at once, a generator 'freezes' its state and resumes execution upon the next call.
Advantages of generators:
- Memory efficiency: No need to store the entire sequence in memory; values are generated on demand.
- Convenience when working with large or infinite sequences.
- Simplification of code: Generators make writing iterators simpler and more understandable.
Example of a generator that yields numbers from 0 to n-1:
def count_up_to(n):
i = 0
while i < n:
yield i
i += 1
for number in count_up_to(5):
print(number)
Output:
0
1
2
3
4
Thus, generators allow efficient and convenient handling of data sequences.