SkillByAIइंटरैक्टिव संस्करण खोलें →

पाठ 36 / 49

इटरेटर प्रोटोकॉल

for loops के पीछे का iterator protocol समझें: __iter__, __next__ और StopIteration।

Iterable बनाम iterator

iterable में __iter__ होता है (iterator लौटाता है)। iterator में __next__ होता है (अगला मान लौटाता है, या StopIteration उठाता है)।

इटरेटर को मैन्युअल चलाना

for x in seq: असल में यह है: iterator लो, बार-बार next() कॉल करो, StopIteration पर रुको। आप इसे मैन्युअल रूप से भी चला सकते हैं।

nums = [10, 20, 30]
it = iter(nums)
print(next(it))   # 10
print(next(it))   # 20
print(next(it))   # 30
# next(it)        # StopIteration