What is a generator in Python?
A generator is a function that uses the yield keyword to give values one at a time, instead of building the whole list in memory. Each time it yields, the function pauses and remembers where it stopped, and it continues from the same place on the next request.
def count_up(n):
i = 1
while i <= n:
yield i
i += 1
for num in count_up(3):
print(num)
Output:
Tutorials Class - Output Window
1
2
3
There is also a short form called a generator expression, which looks like a list comprehension but uses round brackets.
squares = (x * x for x in range(5))
print(sum(squares))
Output:
Tutorials Class - Output Window
30
Generators are a good choice for big data, because values are made only when needed. A generator is also an iterator.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |