Welcome to the “Generators” tutorial!
Overview
Generators produce values one at a time using yield
.
Syntax
def countdown(n):
while n > 0:
yield n
n -= 1
Example
for num in countdown(5):
print(num)
- Generates
5, 4, 3, 2, 1
lazily.
Benefits
- Save memory: values produced on demand.
- Ideal for large data streams.
Key Takeaways
- Use
yield
instead ofreturn
. - Generator functions return generator objects.
Happy coding!
Comments
Post a Comment