🧠 What is a Generator in Python?
A generator is a special type of iterator that produces values lazily—one at a time, and only when needed—without storing them all in memory.
---
❓ How do you create a generator?
✅ Correct answer:
Option 1: Use the
🔥 Simple example:
When you call this function:
Each time you call
---
⛔ Why are the other options incorrect?
- Option 2 (class with
It works, but it’s more complex. Using
- Options 3 & 4 (
Loops are not generators themselves. They just iterate over iterables.
---
💡 Pro Tip:
Generators are perfect when working with large or infinite datasets. They’re memory-efficient, fast, and clean to write.
---
📌 #Python #Generator #yield #AdvancedPython #PythonTips #Coding
🔍By: https://t.me/DataScienceQ
A generator is a special type of iterator that produces values lazily—one at a time, and only when needed—without storing them all in memory.
---
❓ How do you create a generator?
✅ Correct answer:
Option 1: Use the
yield
keyword inside a function.🔥 Simple example:
def countdown(n):
while n > 0:
yield n
n -= 1
When you call this function:
gen = countdown(3)
print(next(gen)) # 3
print(next(gen)) # 2
print(next(gen)) # 1
Each time you call
next()
, the function resumes from where it left off, runs until it hits yield
, returns a value, and pauses again.---
⛔ Why are the other options incorrect?
- Option 2 (class with
__iter__
and __next__
): It works, but it’s more complex. Using
yield
is simpler and more Pythonic.- Options 3 & 4 (
for
or while
loops): Loops are not generators themselves. They just iterate over iterables.
---
💡 Pro Tip:
Generators are perfect when working with large or infinite datasets. They’re memory-efficient, fast, and clean to write.
---
📌 #Python #Generator #yield #AdvancedPython #PythonTips #Coding
🔍By: https://t.me/DataScienceQ
👍6❤2🔥2❤🔥1