Index
Iterators
An iterator is an object in Python that allows you to loop through a collection (like lists, tuples, etc.) one element at a time.
Two key methods:
__iter__()→ returns the iterator object itself.__next__()→ returns the next value from the collection.
Example using a built-in iterator (like a list)
# A list (iterable)
numbers = [1, 2, 3]
# Getting an iterator from the list
my_iter = iter(numbers)
# Accessing elements one by one using next()
print(next(my_iter)) # Output: 1
print(next(my_iter)) # Output: 2
print(next(my_iter)) # Output: 3
# print(next(my_iter)) # Will raise StopIteration error if uncommented
Explanation:
Step 1:
# A list (iterable)
numbers = [1, 2, 3]
numbersis a list, which is an iterable (can be looped through).- It contains three elements:
1,2, and3.
Step 2:
# Getting an iterator from the list
my_iter = iter(numbers)
- We use the
iter()function to convert the list into an iterator object. my_iteris now an iterator, and it remembers its current position.
Step 3:
# Accessing elements one by one using next()
print(next(my_iter)) # Output: 1
print(next(my_iter)) # Output: 2
print(next(my_iter)) # Output: 3
The next() function gets the next value from the iterator:
- 1st call → returns
1 - 2nd call → returns
2 - 3rd call → returns
3
Creating a Custom Iterator:
Let’s create our own iterator that returns numbers from 1 to 5.
class CountToFive:
def __iter__(self):
self.num = 1
return self
def __next__(self):
if self.num <= 5:
val = self.num
self.num += 1
return val
else:
raise StopIteration
# Using the custom iterator
counter = CountToFive()
for i in counter:
print(i)
Output:
1
2
3
4
5
Explanation:
Step1: Class Definition
class CountToFive:
This defines a class named CountToFive. This class will behave like an iterator.
Step 2: __iter__() Method
def __iter__(self):
self.num = 1
return self
- This method is called when iteration starts (e.g., in a
forloop). - It initializes the counter
self.numto 1. - It returns the object itself, which is also an iterator.
Step 3:__next__() Method
def __next__(self):
if self.num <= 5:
val = self.num
self.num += 1
return val
else:
raise StopIteration
- This method returns the next value in the sequence each time it is called.
- If
numis less than or equal to 5:- It stores the current value in
val. - Increments
numby 1. - Returns
val
- It stores the current value in
- If
numis greater than 5, it raisesStopIterationto signal that the iteration is finished.
Step 4: Using the Iterartor
counter = CountToFive()
for i in counter:
print(i)
counter = CountToFive()creates an instance of the class.for i in counter:starts a loop:- It automatically calls
__iter__()to get the iterator. - Then it keeps calling
__next__()to get values untilStopIterationis raised.
- It automatically calls
✅ Real-life Analogy:
Imagine a TV remote (iterator) going through channels (iterable).
You press next to go to the next channel.
Once you’re on the last channel, pressing next shows nothing or error — just like StopIteration.
