🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

Iterators

AI & DATA SCIENCE // iterators

An iterator is any object that implements the iterator protocol — a __next__ method that produces the next value each time it's called, and raises StopIteration when there are no more values.

Syntax

it = iter(some_iterable)
next(it)
next(it)  # ... until StopIteration

Deep Dive Course

Iterables, like lists, strings, and dicts, and iterators are related but distinct: an iterable is anything you can get an iterator from, by calling iter() on it, while an iterator is the object that actually produces values one at a time via next(), and remembers its position between calls. A for loop works by calling iter() on whatever you're looping over to get an iterator, then repeatedly calling next() on it until StopIteration is raised, which the loop catches internally to know when to stop — this is exactly the mechanism that makes for loops work uniformly across every different kind of iterable.

1Understanding Iterators

Iterables, like lists, strings, and dicts, and iterators are related but distinct: an iterable is anything you can get an iterator from, by calling iter() on it, while an iterator is the object that actually produces values one at a time via next(), and remembers its position between calls. A for loop works by calling iter() on whatever you're looping over to get an iterator, then repeatedly calling next() on it until StopIteration is raised, which the loop catches internally to know when to stop — this is exactly the mechanism that makes for loops work uniformly across every different kind of iterable.

💡

An iterator is exhausted after one full pass — once next() has raised StopIteration, calling next() again just raises StopIteration forever; you need a fresh iterator, usually by calling iter() again on the original iterable, to go through the values a second time.

editor.html
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))
localhost:3000

2Practical Example

Here is a real-world application of Iterators showing how it is used in production Python code.

editor.html
class Countdown:
    def __init__(self, start):
        self.current = start
    def __iter__(self):
        return self
    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

for n in Countdown(3):
    print(n)
localhost:3000

3Best Practices

Follow these guidelines when working with Iterators:

1. Implement __iter__ and __next__ on a custom class if you want instances to work directly with for loops and other iteration contexts

2. Remember that an iterator, unlike many iterables like a list, is exhausted after one pass — get a fresh one if you need to iterate again

3. Use the two-argument form of iter() to keep calling a function until it returns a specific sentinel value, a lesser-known but useful pattern

⚠️

Tip: An iterator is exhausted after one full pass — once next() has raised StopIteration, calling next() again just raises StopIteration forever; you need a fresh iterator, usually by calling iter() again on the original iterable, to go through the values a second time.

editor.html
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))
localhost:3000

Examples

Example 01Basic Usage
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))
Example 02Advanced Example
class Countdown:
    def __init__(self, start):
        self.current = start
    def __iter__(self):
        return self
    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

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

Best Practices

  • Implement __iter__ and __next__ on a custom class if you want instances to work directly with for loops and other iteration contexts
  • Remember that an iterator, unlike many iterables like a list, is exhausted after one pass — get a fresh one if you need to iterate again
  • Use the two-argument form of iter() to keep calling a function until it returns a specific sentinel value, a lesser-known but useful pattern

Interview Question

What's the difference between an iterable and an iterator, given that a for loop can work directly with both a list and a custom iterator class?

Hint: Think about which one you get values from directly, and which one you get an iterator out of first.

An iterable is any object you can call iter() on to obtain an iterator — a list is iterable, but calling next() directly on a list itself doesn't work, since a list doesn't track its own iteration position. An iterator is the object actually returned by that iter() call, which does implement __next__ and does track position, producing one value per call until it's exhausted. A for loop always calls iter() first to get an iterator, regardless of whether you handed it a list, a string, or an object that's already its own iterator by implementing __iter__ to return itself.

Exercises

MediumPractice using Iterators in a real scenario.
View Solution
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))
print(next(it))
print(next(it))

Frequently Asked Questions

What's the difference between an iterable and an iterator, given that a for loop can work directly with both a list and a custom iterator class?

An iterable is any object you can call iter() on to obtain an iterator — a list is iterable, but calling next() directly on a list itself doesn't work, since a list doesn't track its own iteration position. An iterator is the object actually returned by that iter() call, which does implement __next__ and does track position, producing one value per call until it's exhausted. A for loop always calls iter() first to get an iterator, regardless of whether you handed it a list, a string, or an object that's already its own iterator by implementing __iter__ to return itself.

Related Functions

for-loopgenerators-yielddunder-methods