Introduction to Iterators

Let's talk about iterators and their purpose.

We have probably been using iterators and generators since we started programming in Python but we may not have realized it. In this chapter, we will learn what an iterator and a generator are. We will also be learning how they are created so we can create our own when we need to.

Iterators

An iterator is an object that will allow us to iterate over a container. The iterator in Python is implemented via two distinct methods: _iter_ and _next_. The _iter_ method is required for our container to provide iteration support. It will return the iterator object itself. But if we want to create an iterator object, then we will need to define _next_ as well, which will return the next item in the container.

Note: In Python 2, the naming convention was slightly different. We still needed_iter_, but_next_ was called next.

Get hands-on with 1200+ tech skills courses.