Python Generators: Implementation and Usage
Page Info
Content
Python Generators: Implementation and Usage
In Python, generators are a way to create iterators using the yield
keyword. A generator produces values one at a time and remembers its state between each yield, allowing memory-efficient iteration over large datasets or infinite sequences.
Generator Function Example
def my_generator(n):
"""Generate numbers from 0 to n-1"""
i = 0
while i < n:
yield i # Return current value and pause
i += 1
# Create generator object
gen = my_generator(5)
# Using generator in a for loop
print("Using for loop:")
for number in gen:
print(number)
Accessing Generator Values Manually with next()
gen2 = my_generator(3)
print("Using next() function:")
print(next(gen2)) # Output: 0
print(next(gen2)) # Output: 1
print(next(gen2)) # Output: 2
# print(next(gen2)) # Raises StopIteration: no more values
Key Concepts
- yield keyword: Temporarily suspends function execution, returns a value, and resumes from the same point on the next call.
- Generator object: Calling a generator function returns a generator object, not a list.
- for loop: Automatically calls
__next__()
on the generator to get each value. - next() function: Manually retrieve the next value using
next(gen)
.
Advantages of Generators
- Memory efficiency: Values are generated on-the-fly instead of storing all values in memory.
- Supports infinite sequences: Combine
while True
andyield
to produce values as needed without memory overload.
SEO Keywords
Python generator, Python yield example, memory efficient iteration Python, Python infinite generator, Python generator for loop, next() generator Python
Use generators in Python to efficiently iterate over large datasets or create infinite sequences while saving memory and maintaining performance.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.