Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟡 Advanced Python  ·  Lesson 22

Iterators और Generators

Iterators और generators क्यों?

Python का हर for loop एक iterator इस्तेमाल करता है – ऐसा object जो एक बार में एक item देता है। Generator अपना iterator बनाने का सबसे आसान तरीका है: एक function जो yield से values एक-एक करके, सिर्फ़ ज़रूरत पड़ने पर बनाता है।

यह बड़े data में बहुत काम आता है: 5 GB की log file पढ़ना, लाखों database rows stream करना, या अनंत series बनाना। List सब कुछ memory में ले आती है; generator सिर्फ़ मौजूदा item रखता है।

for loop असल में कैसे चलता है: iter() और next()

Python – iter_next.py
marks = [78, 91, 66]

it = iter(marks)        # ask the list for an iterator
print(next(it))
print(next(it))
print(next(it))
try:
    next(it)            # nothing left
except StopIteration:
    print("StopIteration – the loop ends here")
78 91 66 StopIteration – the loop ends here

for loop बस एक बार iter() बुलाता है, फिर बार-बार next(), और StopIteration आने पर चुपचाप रुक जाता है।

शब्दअर्थउदाहरण
Iterableजिस पर loop चल सके; iter(x) काम करेlist, tuple, str, dict, set, file, range
Iterator__next__ वाला object; अपनी जगह याद रखता है; एक बार इस्तेमालiter(list) का नतीजा, file objects, generators
Generatoryield वाले function या generator expression से बना iteratordef count(): yield 1, (x*x for x in data)

Iterator class लिखना (लंबा तरीका)

Python – countdown_class.py
class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        value = self.current
        self.current -= 1
        return value

for n in Countdown(3):
    print(n, end=" ")
print("🚀")
3 2 1 🚀

यह चलता है, पर state आपको ख़ुद संभालनी पड़ती है। Generator यही काम चार lines में करता है।

yield वाले generator functions

Python – yield_basics.py
def countdown(start):
    print("generator started")
    while start > 0:
        yield start          # pause here and hand out a value
        start -= 1
    print("generator finished")

gen = countdown(3)
print(type(gen).__name__)    # nothing has run yet
print(next(gen))
print(next(gen))
print(list(gen))             # takes the rest
generator generator started 3 2 generator finished [1]
  • countdown(3) बुलाने पर कोई code नहीं चलता – सिर्फ़ generator object बनता है।
  • हर next() अगले yield तक चलता है, वह value लौटाकर रुक जाता है, और सारे local variables याद रखता है।
  • Function ख़त्म होने पर StopIteration अपने-आप आता है।
returnyield
Function ख़त्म करता हैFunction को रोकता है
एक value देता हैसमय के साथ कई values दे सकता है
Local variables खो जाते हैंLocal variables बने रहते हैं

Memory: list बनाम generator

Python – memory.py
import sys

squares_list = [n * n for n in range(1_000_000)]
squares_gen = (n * n for n in range(1_000_000))     # round brackets

print("list size :", sys.getsizeof(squares_list) // 1024, "KB")
print("gen size  :", sys.getsizeof(squares_gen), "bytes")
print("same total:", sum(squares_list) == sum(squares_gen))
list size : 8250 KB gen size : 200 bytes same total: True
💡 Generator expression

List comprehension के square brackets को round brackets से बदलें, generator बन जाएगा। Function call के अंदर extra brackets छोड़ सकते हैं: sum(x*x for x in data)।

⚠️ Generator सिर्फ़ एक बार इस्तेमाल होता है

ख़त्म होने के बाद वह ख़ाली रहता है। Data दो बार चाहिए तो नया generator बनाएँ या list में रख लें।

असली उदाहरण: बड़ी log file पर data pipeline

Generators को pipes की तरह जोड़ सकते हैं। हर stage एक बार में एक line लेता है, इसलिए यह program 10 lines की file हो या 10 करोड़ lines की, उतनी ही कम memory लेता है।

Python – log_pipeline.py
def read_lines(path):
    with open(path, encoding="utf-8") as f:
        for line in f:                 # files are iterators too
            yield line.rstrip("\n")

def only_errors(lines):
    for line in lines:
        if " ERROR " in line:
            yield line

def parse(lines):
    for line in lines:
        date, time, level, *message = line.split()
        yield {"time": time, "message": " ".join(message)}

errors = parse(only_errors(read_lines("server.log")))
for e in errors:
    print(e["time"], "-", e["message"])
09:02:14 - payment gateway timeout 09:07:03 - database connection refused

अनंत generators और itertools

Python – infinite.py
import itertools

def invoice_numbers(prefix="INV"):
    n = 1
    while True:                    # never ends – that is fine for a generator
        yield f"{prefix}-{n:04d}"
        n += 1

numbers = invoice_numbers()
print(next(numbers), next(numbers))

# take only what you need with islice
print(list(itertools.islice(invoice_numbers("SS"), 3)))

# batches of 2 students (itertools.batched exists from Python 3.12; this works everywhere)
def batches(items, size):
    it = iter(items)
    while chunk := list(itertools.islice(it, size)):
        yield chunk

print(list(batches(["Asha", "Ravi", "Neha", "Kabir", "Isha"], 2)))
INV-0001 INV-0002 ['SS-0001', 'SS-0002', 'SS-0003'] [['Asha', 'Ravi'], ['Neha', 'Kabir'], ['Isha']]

yield from: दूसरे generator को काम सौंपना

Python – yield_from.py
def walk(folder):
    """Yield every file name inside nested folders (a dict tree)."""
    for name, value in folder.items():
        if isinstance(value, dict):
            yield from walk(value)       # hand over to the inner generator
        else:
            yield name

project = {"index.html": 1, "css": {"style.css": 1}, "js": {"app.js": 1, "lib": {"chart.js": 1}}}
print(list(walk(project)))
['index.html', 'style.css', 'app.js', 'chart.js']

आम ग़लतियाँ

ग़लतीनतीजासुधार
एक ही generator पर दो बार loopदूसरा loop कुछ नहीं छापतादोबारा बनाएँ या list इस्तेमाल करें
Generator पर len()TypeErrorsum(1 for _ in gen) से गिनें या list लें
Generator बनाते ही code चलने की उम्मीदnext()/loop तक कुछ नहीं होतायाद रखें: generators lazy होते हैं
बड़ी file के लिए listMemoryError / धीमा programFile पर iterate करें या lines yield करें

अभ्यास

  1. even_numbers(limit) लिखें जो limit तक even numbers yield करे।
  2. marks.csv को line-by-line पढ़कर सिर्फ़ 75 से ज़्यादा marks वाले students yield करने वाला generator लिखें।
  3. आज से शुरू होने वाला dates का अनंत generator बनाएँ (datetime.date और timedelta) और अगले 7 दिन छापें।
  4. sys.getsizeof से [x for x in range(10**6)] और (x for x in range(10**6)) की memory तुलना करें।

सारांश

  • Iterable → loop हो सकता है; iterator → next() से items देता है और अपनी जगह याद रखता है।
  • yield वाला function generator लौटाता है; यह lazy चलता है और हर yield पर रुकता है।
  • Generator expressions ( … ) lists [ … ] से कम memory लेते हैं।
  • Generators जोड़कर कम memory वाली pipelines बनाएँ; slicing और जोड़ने के लिए itertools।
  • Generator एक बार ही इस्तेमाल होता है।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

Iterator और generator में क्या अंतर है?
हर generator एक iterator है, पर हर iterator generator नहीं। Iterator कोई भी object है जिसमें __iter__ और __next__ हों। Generator वह iterator है जो Python आपके लिए yield वाले function या generator expression से बनाता है।
List की जगह generator कब इस्तेमाल करें?
जब data बड़ा हो, file या network से आए, अनंत हो, या loop में सिर्फ़ एक बार चाहिए। Indexing, length, sorting या कई बार पढ़ना हो तो list लें।
क्या generator कोई value return कर सकता है?
हाँ। Generator के अंदर return उसे ख़त्म करता है, और value StopIteration exception में रखी जाती है। yield from वह value प्राप्त करता है, जो एक generator से दूसरे को काम सौंपने में उपयोगी है।
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.
अगला topicre Module के साथ Regular Expressions आपकी प्रगति: 22 / 66 (33%) · Lesson 23 / 66 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें