# Python's Generators and Yield

Python Basics 3 / 4
1 min read

Generators in Python are a way to create iterators using the yield keyword. Here’s an example:

def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)

Generators are memory-efficient and allow you to work with large datasets without loading them entirely into memory.

Running Python Generators
python -c "def count_up_to(n):\n count = 1\n while count <= n:\n yield count\n count += 1\nfor number in count_up_to(5):\n print(number)"
Next: Python's Context Managers and the with Statement
My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


Python Basics Series

Comments