MyInternships.in

Python Advanced

Python Iterators

An iterator is an object that lets you step through a collection of values one at a time. Understanding iterators helps you see what's really happening under the hood of every for loop.


Iterable vs Iterator

An iterable is anything you can loop over, like a list, tuple, string, or dictionary — it has an __iter__ method that produces an iterator. An iterator is the object that actually tracks your position and hands out one value at a time using __next__. Every iterator is iterable, but not every iterable is an iterator.

Getting an iterator from a list
Python
numbers = [10, 20, 30]
it = iter(numbers)

print(next(it))
print(next(it))
print(next(it))
Output
Output
10
20
30

StopIteration

Once an iterator runs out of values, calling next() again raises a StopIteration exception. A for loop catches this exception automatically, which is why loops end cleanly without you ever seeing an error.

What happens when values run out
Python
it = iter([1, 2])
print(next(it))
print(next(it))
print(next(it))  # raises StopIteration

Writing Your Own Iterator

You can build a custom class as an iterator by defining both __iter__ (which returns self) and __next__ (which returns the next value or raises StopIteration). This pattern is the foundation behind generators and many built-in tools like enumerate and zip.

A simple countdown iterator
Python
class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        value = self.current
        self.current -= 1
        return value

for n in Countdown(3):
    print(n)
💡

Every for loop in Python calls iter() on the object once, then next() repeatedly until StopIteration is raised — that is the entire mechanism behind looping.

ConceptWhat it does
IterableHas __iter__(); can produce an iterator
IteratorHas __iter__() and __next__(); tracks state
iter(x)Returns an iterator for iterable x
next(it)Returns the next value or raises StopIteration
ℹ️

Generators (functions using yield) are the easiest way to write iterators in Python without manually managing __iter__ and __next__.

Frequently Asked Questions

What is the difference between an iterable and an iterator in Python?+

An iterable is any object you can loop over (like a list or string) because it defines __iter__. An iterator is the object returned by iter() that actually produces values one at a time via __next__ and remembers its position.

Why does a for loop never raise StopIteration in my code?+

The for loop catches StopIteration internally. When the iterator signals it has no more values, the loop simply stops instead of letting the exception propagate to your code.

Are lists iterators?+

No. Lists are iterables, not iterators — they don't have a __next__ method. Calling iter() on a list creates a separate list_iterator object that does the actual stepping through.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships