← Back to Python Course | Chapter 11: Advanced Python | Lesson 1 of 12

Python Iterators

एक iterator आपको किसी collection से एक-एक करके item देता है, जैसे कोई dealer ताश के पत्ते एक-एक करके बाँटता है। यह याद रखता है कि वह कहाँ है, ताकि आप बस अगला माँगते रहें।
Syntax
python
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

python
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

python
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

python
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

python
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

python
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)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.