


Khusboo Tayal
Iterators are a core concept in Python, allowing you to traverse through a collection or sequence of data. Whether you’re using a for loop, list, tuple, or even file objects—iterators are working behind the scenes.
This guide will help you understand what iterators are, how they work, and how to create your own custom iterator in Python.
An iterator is an object in Python that allows you to traverse through all the elements of a collection, one element at a time.
To be an iterator, an object must implement two methods:
numbers = [1, 2, 3] # Iterable it = iter(numbers) # Iterator created from iterable print(next(it)) # Output: 1 print(next(it)) # Output: 2
When you use a for loop in Python:
for char in "Python":
print(char)Behind the scenes, Python does the following:
s = "Python"
it = iter(s)
while True:
try:
print(next(it))
except StopIteration:
breakYou can create your own iterator by defining a class with __iter__() and __next__() methods.
class CountToFive:
def __init__(self):
self.num = 1
def __iter__(self):
return self
def __next__(self):
if self.num <= 5:
value = self.num
self.num += 1
return value
else:
raise StopIteration
counter = CountToFive()
for i in counter:
print(i)Output:
1 2 3 4 5
You can use the built-in iter() function to turn an iterable into an iterator.
lst = [10, 20, 30] it = iter(lst) print(next(it)) # Output: 10
The built-in next() function retrieves the next item from an iterator.
fruits = iter(["apple", "banana", "cherry"])
print(next(fruits)) # Output: apple
print(next(fruits)) # Output: banana
You can also provide a default value to avoid exceptions:
print(next(fruits, "No more fruits")) # Output: cherry
print(next(fruits, "No more fruits")) # Output: No more fruits
The StopIteration exception is raised automatically when there are no more elements to iterate.
You usually won’t see it in for loops because they handle it internally, but you might see it when using next() manually.
You can create infinite iterators, but use them carefully.
class InfiniteCounter:
def __init__(self):
self.num = 0
def __iter__(self):
return self
def __next__(self):
self.num += 1
return self.num
counter = InfiniteCounter()
for i in counter:
if i > 5:
break
print(i)Both iterators and generators allow iteration, but generators are more concise and memory-efficient.
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1Iterators are often used in:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Iterators in Python are an essential part of understanding how data traversal works. They provide a clean and efficient way to loop through sequences, create custom iteration logic, and build powerful Python applications.
Understanding the difference between iterables and iterators, and knowing how to implement custom iterators, will help you write cleaner and more Pythonic code.
Q1: Is every list an iterator?
No, a list is an iterable. You can get an iterator from it using iter(list).
Q2: What happens if you call next() after the iterator is exhausted?
It raises a StopIteration exception.
Q3: How is an iterator different from a generator?
An iterator requires a class with __iter__() and __next__(). A generator is created with the yield keyword and is more memory-efficient.
Subscribe to our newsletter to get the latest Python tutorials, project ideas, and updates right to your inbox.
#python #pythoniterators #iterablevsiterator #pythontutorial #pythonforbeginners #nextfunction #iterfunction #customiterator #objectorientedpython