Learn Python
>>> advanced_python.iterators

Iterators in Python

#concept

An iterator is an object that produces its items one at a time, on demand, remembering exactly where it left off between requests. Anything Python can loop over with a for loop — lists, strings, dictionaries, files — is doing so through this same underlying mechanism: getting an iterator from the collection, then repeatedly asking it for the next item until there are none left.

#how it works
1

iter(obj) gets an iterator

From any iterable object, like a list or string.

2

next(iterator) advances it

Returns the next item, and permanently moves the iterator forward.

3

Running out raises StopIteration

When there are no more items left, calling next() raises this exception.

4

A for loop automates all of this

Calling iter() once, then next() repeatedly, and catching StopIteration to end cleanly.

5

Custom classes can be iterable too

By implementing __iter__ and __next__, letting them work with a for loop the same way a list does.

#example
numbers = [10, 20, 30]
it = iter(numbers)
 
print(next(it))
print(next(it))
print(next(it))
Output
10
20
30
1iter(numbers) creates an iterator, an object that tracks position within the list separately from the list itself.
2Each next(it) call retrieves the next item and moves the iterator forward permanently — calling it again never returns to an earlier item.
3A fourth next(it) call here would raise StopIteration, since all three items have already been retrieved — this is exactly what a for loop catches automatically to know when to stop.
#use cases
Understanding what actually happens behind the scenes every time a for loop runs
Building a custom class that can be looped over directly with for item in my_object, by implementing __iter__ and __next__
Processing a sequence of unknown or infinite length without needing to know its size in advance
Appreciating why a used-up iterator can't simply be 'rewound' — a fresh one has to be created instead

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.