Iterators & the Iterator Protocol
"Iterable" koi bhi object hai jispar for loop chal sakta hai (list, string, dict). "Iterator" wo object hai jo actually values produce karta hai, ek time par ek — __next__() call hone par agli value deta hai, ya StopIteration raise karta hai jab khatam ho jaaye.
iter() function kisi iterable se ek iterator banata hai. next() function iterator se agli value nikalta hai. for loop internally exactly yehi karta hai — automatically, tumhare liye.
nums = [1, 2, 3]
it = iter(nums) # iterator banao
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3
# print(next(it)) # StopIteration error — khatam ho gaya
# for loop internally ye hi karta hai:
for n in nums:
print(n)
# yehi hai: it = iter(nums); while True: try: n = next(it) except StopIteration: break- Iterable = for loop mein use ho sakta hai (list, dict, string)
- Iterator = actual values produce karta hai, __next__() se
- for loop internally iter()/next() hi use karta hai
Apni khud ki class ko iterable/iterator banane ke liye __iter__ aur __next__ dunder methods implement karo — poora control milta hai custom iteration logic par.
class CountUp:
def __init__(self, max_val):
self.max_val = max_val
self.current = 0
def __iter__(self):
return self # khud hi iterator hai
def __next__(self):
if self.current >= self.max_val:
raise StopIteration
self.current += 1
return self.current
for num in CountUp(5):
print(num) # 1 2 3 4 5Kuch iterators (jaise itertools.count()) infinite hote hain — kabhi StopIteration nahi dete. Loop mein use karte waqt explicit break condition zaroori hai, warna infinite loop ban jaayega.
from itertools import count
for num in count(start=1):
print(num)
if num >= 5:
break # ZAROORI — warna infinite chalega