Search⌘ K

Iterators

Explore the concept of iterators in Python, including how to use built-in iterators with lists and other collections. Learn to create custom iterable classes by implementing __iter__ and __next__ methods, enabling you to control iteration behavior and handle StopIteration properly in loops.

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) ...