Junior — Middle
Can you give an example of using the standard generator from Python's built-in capabilities?
sobes.tech AI
Answer from AI
In Python, a standard generator is a function that uses the keyword yield to produce values step-by-step without creating the entire list in memory.
Here's an example of a simple generator that returns numbers from 0 to n-1:
def count_up_to(n):
count = 0
while count < n:
yield count
count += 1
for number in count_up_to(5):
print(number)
Output:
0
1
2
3
4
This approach is efficient when working with large amounts of data, as values are generated on demand.