Interview question
What is the iterator protocol and how do __iter__ and __next__ work? Iterator protocol क्या है और __iter__ और __next__ कैसे काम करते हैं?
Answer
The iterator protocol requires an object to implement __iter__ (returns the iterator itself) and __next__ (returns the next value or raises StopIteration). This is what powers 'for' loops behind the scenes.
class CountUpTo:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self # the object IS its own iterator
def __next__(self):
if self.current >= self.limit:
raise StopIteration # signals the end of iteration
self.current += 1
return self.current
counter = CountUpTo(3)
print(next(counter)) # 1
print(next(counter)) # 2
print(next(counter)) # 3
# print(next(counter)) # StopIteration
# 'for' loops use this protocol automatically
for num in CountUpTo(5):
print(num) # 1, 2, 3, 4, 5
# What a for loop actually does under the hood:
iterator = iter(CountUpTo(3)) # calls __iter__
while True:
try:
value = next(iterator) # calls __next__
print(value)
except StopIteration:
break
# Iterable vs Iterator - an important distinction
# Iterable: has __iter__, can produce an iterator (e.g. a list)
# Iterator: has __iter__ AND __next__, tracks its own state
my_list = [1, 2, 3] # iterable, but not an iterator itself
# next(my_list) # TypeError: 'list' object is not an iterator
my_iterator = iter(my_list) # NOW it's an iterator
print(next(my_iterator)) # 1Iterator protocol के लिए object को __iter__ (खुद iterator return करे) और __next__ (अगली value return करे या StopIteration raise करे) implement करना ज़रूरी है। यही 'for' loops के पीछे का mechanism है।
class CountUpTo:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current >= self.limit:
raise StopIteration
self.current += 1
return self.current
counter = CountUpTo(3)
print(next(counter)) # 1
print(next(counter)) # 2
# 'for' loops यह protocol automatically use करते हैं
for num in CountUpTo(5):
print(num)
# for loop असल में क्या करता है:
iterator = iter(CountUpTo(3))
while True:
try:
value = next(iterator)
print(value)
except StopIteration:
break
# Iterable बनाम Iterator
my_list = [1, 2, 3] # iterable, iterator नहीं
# next(my_list) # TypeError
my_iterator = iter(my_list)
print(next(my_iterator)) # 1Was this answer clear?