A Generator is a special type of function that returns an iterator. Instead of returning all values at once, it generates values one at a time using the yield keyword.
Generators are memory-efficient and useful when working with large datasets.
Creating a Generator
A generator function uses the yield keyword instead of return.
Example
def numbers():
yield 1
yield 2
yield 3
for num in numbers():
print(num)
Output:
1
2
3
Generator with next()
You can retrieve values one by one using the next() function.
Example
def numbers():
yield 10
yield 20
yield 30
generator = numbers()
print(next(generator))
print(next(generator))
print(next(generator))
Output:
10
20
30
Difference Between return and yield
Using return
def test():
return 10
return 20
print(test())
Output:
10
Using yield
def test():
yield 10
yield 20
for value in test():
print(value)
Output:
10
20
Generator with Loop
Example
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)
Output:
1
2
3
4
5
Generator Expression
A generator expression is similar to a list comprehension but uses parentheses.
Example
numbers = (x * x for x in range(5))
for num in numbers:
print(num)
Output:
0
1
4
9
16
Memory Efficient Example
List
numbers = [x for x in range(1000000)]
Generator
numbers = (x for x in range(1000000))
The generator uses much less memory because values are generated only when needed.
Infinite Generator
Example
def infinite_numbers():
num = 1
while True:
yield num
num += 1
generator = infinite_numbers()
print(next(generator))
print(next(generator))
print(next(generator))
Output:
1
2
3
Summary
- Generators are functions that use the
yieldkeyword. - They generate values one at a time.
- Generators are memory-efficient.
next()retrieves the next generated value.- Generator expressions use parentheses
(). - Generators are useful for large datasets and infinite sequences.
- They automatically implement the iterator protocol.