T
Tech Town
Log InSign Up Free
← Back to Blog

June 19, 2025 · admin

Python Iterators


๐Ÿ”„ 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