Iterators
In this basic post we'll explain the basics of iterators.
A Python Iterator
- If a python object contains some collection of objects, we need a way to get these object, one at a time.
- Note that:
- A specific order is optional, but we must make sure that:
- ..we get each object ONCE, and..
- ..eventually we get ALL objects.
- Python iterators implement the special method next
- Each call to this special method (or a call to the next() built-in function which is the same thing) will return another object from the collection of objects.
An Iterable Object
- An iterable object, implements the iter special method
- If you call this special method (or the built-in iter() function which does the same thing), the iterable object will return an Iterator (that implements the next special method).
- Here's an example, base on the range object:
1>>> r1 = range(5)
2>>> it = r1.__iter__()
3>>> it
4<range_iterator object at 0x000001E3E5A2A0B0>
5>>> it.__next__()
60
7>>> it.__next__()
81
9>>> it.__next__()
102
11>>> it.__next__()
123
13>>> it.__next__()
144
15>>> it.__next__()
16Traceback (most recent call last):
17 File "<stdin>", line 1, in <module>
18StopIteration
19>>>):
Creating our own Iterable and Iterator
- We'll just implement everything needed:
- Class Letters is an iterable, so it implements the iter special method
- When called, iter returns an instance of LetterIter, which is an iterator (it implements next)
1class LetterIter:
2 def __init__(self, the_letters):
3 self.letters = the_letters
4 self.current = -1
5
6 def __next__(self):
7 self.current += 1
8 if self.current == len(self.letters):
9 raise StopIteration
10 return self.letters[self.current]
11
12class Letters:
13 def __init__(self):
14 self.letters = ['a','b','c','d','e']
15
16 def __iter__(self):
17 return LetterIter(self.letters)
18
19
20
21l1 = Letters()
22for l in l1:
23 print(l)
- Creating iterators involves writing all those methods, but there is a better way using generators.
We'll cover generators in another post.