Iterators & generators
An iterator supplies values one at a time. A generator function uses yield to pause and later resume. This can avoid building a large list in memory. A generator is exhausted after its values are consumed.
हिन्दी में समझें
इटरेटर एक-एक मान देता है। जनरेटर yield पर रुककर बाद में चलता है। इससे बड़ी लिस्ट की मेमोरी बच सकती है। सारे मान लेने के बाद जनरेटर समाप्त होता है।
अभ्यास: countdown(4) को कॉल करें और उसके मानों की लिस्ट प्रिंट करें।
Hinglish mein samjhein
Iterator ek-ek value deta hai. Generator yield par pause aur resume hota hai. Badi list banane ki memory bachti hai. Consume hone ke baad generator exhausted hota hai.
Practice: countdown(4) call karke values ki list print karo.
A small Python example
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(3)))The browser playground runs real Python with Pyodide. Use sample variables instead of interactive input(). Browser package support differs from desktop Python.
Try this example in the Python playground →Practise this idea
Call countdown(4) and print its list of values.
Check answer & explanation
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(4)))The generator yields the current value before decreasing it. Starting at 4 therefore gives 4, 3, 2 and 1.
Stuck in the course? Choose Check answer for either the challenge or quiz. Read the explanation and continue to the next lesson at your own pace.
Check your understanding
Which keyword yields one value?
Check the quiz answer
yield
yield suspends a generator and provides its next value.
References & corrections
Use the official Python documentation for full language rules. Read how these lessons are made and checked. Found a mistake? Report it to Excel Keys with this lesson URL and a reproducible example.