Last Updated : 10 Mar, 2025
In Python, we often need to make objects iterable, allowing them to be looped over like lists or other collections. Instead of using complex generator loops, Python provides the __iter__() and __next__() methods to simplify this process.
Iterator Protocol:
Example: Creating an Iterable Object
Python
a = ['a', 'e', 'i', 'o', 'u']
iter_a = iter(a)
print(next(iter_a))
print(next(iter_a))
print(next(iter_a))
print(next(iter_a))
print(next(iter_a))
Explanation: List a is converted into an iterator iter_a and next() retrieves each element sequentially. Once exhausted, further calls to next(iter_a) raise a StopIteration exception.
Python __iter__()The __iter__() function in Python returns an iterator for the given object (e.g., array, set, tuple, or a custom object). It creates an object that can be accessed one element at a time using __next__(). This is particularly useful when dealing with loops.
Syntax:
iter(object)
iter(callable, sentinel)
object: The object whose iterator is created. It can be a collection like a list or a user-defined object.
callable, sentinel:
Example: Using iter(callable,sentinel)
Python
import random
rand_iter = iter(lambda: random.randint(1, 10), 5) # Stops when 5 is generated
for num in rand_iter:
print(num)
Explanation: This code creates an iterator that generates random numbers from 1 to 10, stopping when 5 appears. The for loop prints numbers until 5 is encountered, making the output vary each run.
Python __next__()The __next__() function in Python returns the next element of an iteration. If there are no more elements, it raises the StopIteration exception. It is part of the iterable and iterator interface, which allows us to create custom iterable objects, such as generators, and control how elements are retrieved one at a time.
Example 1. Using __next__() in loop Python
a = [11, 22, 33, 44, 55]
iter_a = iter(a)
while True:
try:
print(iter_a.__next__())
except StopIteration:
break
Explanation: List a is converted into an iterator iter_a and a while True loop is used to retrieve elements using __next__(). A try-except block handles StopIteration, ensuring iteration stops gracefully when the iterator is exhausted.
Example 2. Exception handling Python
a = ['Cat', 'Bat', 'Sat', 'Mat']
iter_a = iter(a)
try:
print(iter_a.__next__())
print(iter_a.__next__())
print(iter_a.__next__())
print(iter_a.__next__())
print(iter_a.__next__()) # Raises StopIteration error
except StopIteration:
print("\nThrowing 'StopIterationError': Cannot iterate further.")
Cat Bat Sat Mat Throwing 'StopIterationError': Cannot iterate further.
Explanation: List a
is converted into an iterator iter_a
and__next__()
retrieves elements sequentially. When exhausted, StopIteration
is caught, displaying a custom message.
We can implement the iterator protocol in user-defined classes by defining __iter__() and __next__() methods. The __iter__() method should return the iterator object and __next__() should return the next element in the sequence.
Example:
Python
class Counter:
def __init__(self, start, end):
self.num = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.num > self.end:
raise StopIteration
else:
self.num += 1
return self.num - 1
# Driver code
if __name__ == '__main__':
a, b = 2, 5
c1 = Counter(a, b)
c2 = Counter(a, b)
# Iteration without using iter()
print("Print the range without iter():")
for i in c1:
print("Counting:", i)
print("\nPrint the range using iter():")
# Using iter()
obj = iter(c2)
try:
while True: # Iterate until StopIteration is raised
print("Counting:", next(obj))
except StopIteration:
print("\nIteration completed.")
Print the range without iter(): Counting: 2 Counting: 3 Counting: 4 Counting: 5 Print the range using iter(): Counting: 2 Counting: 3 Counting: 4 Counting: 5 Iteration completed.
Explanation: The Counter class iterates from start to end, with __iter__() returning itself and __next__() incrementing until StopIteration. The first loop iterates over c1, while the second uses iter(c2) and next(obj), handling exhaustion gracefully.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4