Lesson 81 +10 XP

Iterators

Iterators

An iterator is an object that lets you walk through a collection one item at a time. Lists, tuples, dicts, and strings are iterable.

Iterables and iterators

  • An iterable is something you can loop over, like a list.
  • An iterator is the object that does the stepping.
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
    print(x)

Create an iterator with iter()

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))  # apple
print(next(myit))  # banana
print(next(myit))  # cherry

next() steps through

Each next() call returns the next item. When there are no more items, it raises StopIteration.

Strings are iterable too

mystr = "banana"
myit = iter(mystr)
print(next(myit))  # b
print(next(myit))  # a

Loop through an iterator

The for loop uses iterators under the hood. This:

for x in mytuple:
    print(x)

is the same as calling iter() and next() in a loop.

Make your own class iterable

Implement __iter__ and __next__:

class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        x = self.a
        self.a += 1
        return x

myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))  # 1
print(next(myiter))  # 2

Stop with StopIteration

Raise StopIteration to end your own iterator:

class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        if self.a <= 20:
            x = self.a
            self.a += 1
            return x
        else:
            raise StopIteration

TL;DR

  • Iterators step through collections item by item.
  • iter() makes an iterator; next() pulls values.
  • The for loop uses iterators automatically.
  • Custom iterators implement __iter__ and __next__.
  • StopIteration signals the end.