🔄 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 raises StopIteration when 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

TermDescription
IterableObject you can loop over (like a list, string, etc.)
IteratorObject 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

FeatureSyntax / MethodUse Case
Create iteratoriter(obj)Get iterator from iterable
Next itemnext(iterator)Manually fetch next value
Custom iteratorDefine __iter__, __next__Build advanced or infinite iterators
Stop iterationraise StopIterationSignal 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