An iterator in Python is an object that allows sequential traversal (iteration) of elements from a collection such as a list, tuple, set, or dictionary — one item at a time.
Iterators provide a way to access elements without using indexing, and are fundamental to Python’s looping constructs like for loops.
🔹 Key Concepts
| Concept | Description |
|---|---|
| Iterable | Any object that can return an iterator using iter(). Examples: list, tuple, dict, set, str. |
| Iterator | An object that produces data one element at a time using the next() function. |
| Iteration | The process of going through elements of an iterable using an iterator. |
| StopIteration | An exception raised automatically when no more elements are left to iterate. |
🔹 Iterator Protocol
An object is an iterator if it implements the following two methods:
__iter__()→ returns the iterator object itself.__next__()→ returns the next value from the data source.
When there are no more items, __next__() raises a StopIteration exception.
🧩 Example 1: Using iter() and next()
numbers = [1, 2, 3, 4]
iterator = iter(numbers) # Create an iterator object
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
print(next(iterator)) # 4Output:
1
2
3
4(If you call next(iterator) again → it raises StopIteration.)
🧩 Example 2: Iterating Using a for Loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: # Internally uses iter() and next()
print(fruit)Output:
apple
banana
cherryExplanation:
The for loop automatically:
- Calls
iter(fruits)to get an iterator. - Repeatedly calls
next()untilStopIterationis raised.
🧩 Example 3: Creating a Custom Iterator Class
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self # Returns itself as iterator
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
num = self.current
self.current += 1
return num
for i in Counter(1, 5):
print(i)Output:
1
2
3
4
5🧩 Example 4: Using Iterators with Strings
word = "Dheeraj"
it = iter(word)
print(next(it))
print(next(it))
print(next(it))Output:
D
h
e🧩 Example 5: Handling StopIteration Exception
nums = [10, 20]
it = iter(nums)
try:
print(next(it))
print(next(it))
print(next(it)) # No more elements
except StopIteration:
print("End of iteration reached")Output:
10
20
End of iteration reached🔹 Difference Between Iterable and Iterator
| Feature | Iterable | Iterator |
|---|---|---|
| Definition | Object that can return an iterator using iter(). | Object that produces elements one by one using next(). |
| Examples | list, tuple, dict, str, set | Objects returned by iter() function. |
| Methods | Has __iter__() method. | Has both __iter__() and __next__() methods. |
| Usage | Used in loops like for or comprehension. | Used when you need manual iteration with next(). |
🔹 In Summary
- An iterator is an object that represents a stream of data.
- It uses the
iter()andnext()functions to traverse items one by one. forloops internally use the iterator protocol.- Custom iterators can be created by defining
__iter__()and__next__()methods. - When no more data is available, a
StopIterationexception is raised.
✅ In short:
Iterator = object that remembers where it is during iteration and fetches next data only when requested.
