Iterators

Learn about the concept of iterators in Python.

Introduction to iterators

An iterable object is any object that can be stepped through. Iterable objects include lists, sets, tuples, strings, dictionaries, ranges, and files. An iterator is an object that implements a method for stepping through the elements of an iterable.

For example, you can get a list iterator by saying it = iter([2, 3, 5]). You can step through the elements of this list by repeatedly calling next(it). This will return 2, then 3, and then 5. Yet another call to next(it) will raise a StopIteration exception.

Get hands-on with 1200+ tech skills courses.