Python Iterators
In this page:
class IteratorClass:
def __iter__(self):
return self
def __next__(self):
# return next value or raise StopIteration
iterator = iter(iterable)
next(iterator)
Iterable बनाम Iterator
Iterable वह कुछ भी है जिस पर आप for statement से loop कर सकते हैं (list, string, dict) -- iterator वह अलग object है जो वाकई track रखता है कि आप उस sequence में कहाँ हैं और हर बार पूछे जाने पर अगला element लौटाता है।
उदाहरण: Iterable vs. Iterator
numbers = [1, 2, 3]
print(hasattr(numbers, "__iter__")) # lists are iterable
it = iter(numbers)
print(hasattr(it, "__next__")) # the iterator object supports next()
iter() और next() Functions
iter(some_list) किसी iterable को iterator object में बदल देता है, और बार-बार next(that_iterator) call करना एक बार में एक element लाता है, हर call के साथ internal position आगे बढ़ाता है -- for loop hood के नीचे बिल्कुल यही अपने आप करता है।
उदाहरण: The iter() and next() Functions
numbers = [1, 2, 3]
it = iter(numbers) # converts the list into an iterator
print(next(it)) # advances and returns the first value
print(next(it)) # advances and returns the second value
Custom Iterators बनाना
अपनी iterator class लिखने का मतलब है __iter__ (जो सामान्यतः self लौटाता है) और __next__ (जो हर बार call होने पर अगला value compute करके लौटाता है) implement करना -- ये दोनों methods मिलकर किसी object को for loop में उपयोग करने लायक बनाते हैं।
उदाहरण: Creating Custom Iterators
class Counter:
def __init__(self, limit):
self.n = 0
self.limit = limit
def __iter__(self): # returns itself, making the object an iterator too
return self
def __next__(self):
if self.n >= self.limit:
raise StopIteration # signals the loop to stop
self.n += 1
return self.n
for value in Counter(3):
print(value)
StopIteration Exception
जब देने के लिए कोई item बचे न रहें, तो आपके __next__ method को StopIteration raise करना होता है -- for loop internally इस specific exception पर नज़र रखता है और इसे साफ़-सुथरे तरीके से loop रोकने के संकेत के रूप में इस्तेमाल करता है, न कि इसे unhandled error मानकर।
उदाहरण: The StopIteration Exception
numbers = iter([1])
print(next(numbers))
try:
next(numbers) # no items left
except StopIteration:
print("No more items")
Iterators के व्यावहारिक उपयोग
चूँकि iterator explicitly पूछे जाने पर ही अगला value compute करता है, उसे कभी पूरी sequence एक साथ memory में रखने की ज़रूरत नहीं पड़ती -- यह lazy evaluation ही iterators को बहुत बड़े या यहाँ तक कि effectively infinite data sequences को process करने के लिए efficient बनाता है।
उदाहरण: Practical Uses of Iterators
def count_up_to(limit):
n = 1
while n <= limit:
yield n # produces one value at a time, lazily
n += 1
for value in count_up_to(3):
print(value)
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: