Python - Iterators
When working with loops in Python, you often use for loops to go through lists, tuples, or other collections. But have you ever wondered how Python actually goes through these items one by one?
The answer is Iterators.
Iterators are a powerful concept that allows you to traverse through data efficiently.
In this tutorial, you will learn what iterators are, how they work, and how to create your own iterators in Python.
What is an Iterator?
An iterator is:
An object that allows you to access elements of a collection one at a time.
It follows the iterator protocol in Python.
Iterator Protocol
An object is an iterator if it implements:
__iter__()→ returns the iterator object itself__next__()→ returns the next value
Iterable vs Iterator
| Iterable | Iterator |
|---|---|
| Object that can be looped | Object that produces values one at a time |
| Example: list, tuple | Example: result of iter() |
| Cannot directly use next() | Supports next() |
Creating an Iterator
Python provides the iter() function to create an iterator.
Example
numbers = [1, 2, 3]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))Output
1
2
3How Iterators Work
iter()converts iterable into iteratornext()fetches values one by one- When no values remain →
StopIterationerror
Example with StopIteration
numbers = [1, 2]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it)) # Error hereUsing Iterator in For Loop
Python automatically uses iterators in loops.
numbers = [1, 2, 3]
for n in numbers:
print(n)Behind the Scene
The loop does this internally:
it = iter(numbers)
while True:
try:
value = next(it)
print(value)
except StopIteration:
breakCreating Custom Iterator
You can create your own iterator class.
Example
class MyNumbers:
def __init__(self):
self.num = 1
def __iter__(self):
return self
def __next__(self):
if self.num <= 5:
val = self.num
self.num += 1
return val
else:
raise StopIteration
obj = MyNumbers()
it = iter(obj)
for i in it:
print(i)Output
1
2
3
4
5Why Use Iterators?
Iterators are useful because they:
- Save memory
- Process data lazily
- Improve performance
- Handle large datasets efficiently
Iterator vs List
| Feature | List | Iterator |
| Memory | High | Low |
| Speed | Fast access | Lazy access |
| Storage | All data stored | One item at a time |
Real-World Example: Streaming Data
def stream_data():
yield "data1"
yield "data2"
yield "data3"
for data in stream_data():
print(data)Note
Generators (using yield) are a special type of iterator.
Infinite Iterator Example
class Count:
def __init__(self):
self.num = 1
def __iter__(self):
return self
def __next__(self):
val = self.num
self.num += 1
return val
counter = Count()
print(next(counter))
print(next(counter))Caution
Infinite iterators must be handled carefully to avoid endless loops.
When to Use Iterators
✔ Large data processing
✔ File reading
✔ Streaming APIs
✔ Infinite sequences
✔ Memory-efficient loops
Advantages of Iterators
- Memory efficient
- Faster processing for large data
- Lazy evaluation
- Clean code structure
Common Mistakes
1. Forgetting StopIteration
2. Reusing exhausted iterator
3. Confusing iterable and iterator
Best Practices
1. Use iter() when needed
it = iter(data)2. Prefer for-loops for simplicity
3. Use generators for large data
Summary
Iterators in Python allow you to traverse through data one element at a time efficiently. They are the backbone of Python loops and help manage memory effectively.
Key Takeaways
- Iterator returns items one by one
- Uses
__iter__()and__next__() - Built into Python for loops
- Saves memory
- Useful for large datasets and streaming
Understanding iterators is essential for mastering Python’s data handling and performance optimization.


0 Comments