๐ Python Iterators โ Powering Loops Behind the Scenes | TechTown.in
Ever wondered how for loops in Python actually work?
Behind the scenes, Python uses iterators โ a powerful tool that gives you one item at a time from a collection, allowing efficient looping without loading everything into memory.
In this guide, weโll explore what iterators are, how they work, and how you can create your own custom iterators in Python.
๐ง What is an Iterator?
An iterator is an object in Python that allows one-at-a-time traversal through all the elements of a collection (like lists, tuples, sets, or even strings).
To qualify as an iterator, an object must implement two built-in methods:
__iter__()โ returns the iterator object itself__next__()โ returns the next value and raisesStopIterationwhen done
๐ Example: Using a Built-in Iterator
fruits = ["apple", "banana", "cherry"]
my_iter = iter(fruits)
print(next(my_iter)) # Output: apple
print(next(my_iter)) # Output: banana
print(next(my_iter)) # Output: cherry
If you call next() again โ it throws StopIteration.
๐ฆ All Loops Use Iterators Internally
for fruit in fruits:
print(fruit)
โ This is just a shortcut for:
iter_obj = iter(fruits)
while True:
try:
item = next(iter_obj)
print(item)
except StopIteration:
break
โ๏ธ Create Your Own Iterator (Custom Class)
You can build your own class-based iterator by defining __iter__() and __next__():
class Counter:
def __init__(self, limit):
self.current = 1
self.limit = limit
def __iter__(self):
return self
def __next__(self):
if self.current <= self.limit:
val = self.current
self.current += 1
return val
else:
raise StopIteration
count = Counter(3)
for num in count:
print(num)
๐ฏ Output:
1
2
3
๐ Key Differences: Iterable vs Iterator
| Term | Description |
|---|---|
| Iterable | Object you can loop over (like a list, string, etc.) |
| Iterator | Object with __next__() and __iter__() |
๐ You can get an iterator from an iterable using the iter() function.
๐งช Real-Life Use Case: Paginated Results
Imagine you’re showing products page-by-page from a database. Instead of loading 10,000 items at once, you can build a custom iterator that fetches 10 at a time using __next__().
This saves memory and improves performance.
โ Summary โ Python Iterators Cheat Sheet
| Feature | Syntax / Method | Use Case |
|---|---|---|
| Create iterator | iter(obj) | Get iterator from iterable |
| Next item | next(iterator) | Manually fetch next value |
| Custom iterator | Define __iter__, __next__ | Build advanced or infinite iterators |
| Stop iteration | raise StopIteration | Signal that the loop should end |
๐ Final Thoughts
Python iterators power some of the most efficient and scalable code structures behind the scenes. From for-loops and generators to reading large files and streaming data, iterators let you work with sequences efficiently โ one item at a time.
Once you master them, youโll write cleaner, faster, and more Pythonic code.
๐ Keep mastering Python essentials at TechTown.in