Iterator & Iterable
Iterators and Iterables
We could create iterator objects by simply implementing:
a
__next__method that returns the next element in the containeran
__iter__method that just returns the object itself (the iterator object)
However, we had two outstanding issues/questions:
when we looped over the iterator using a
forloop (or a comprehension, or other functions that do some form of iteration), we saw that the__iter__was always called first.the iterator gets exhausted after we have finished iterating it fully - which means we have to create a new iterator every time we want to use a new iteration over the collection - can we somehow avoid having to remember to do that every time?
class Cities:
def __init__(self):
self._cities = ['New York', 'Newark', 'New Delhi', 'Newcastle']
def __len__(self):
return len(self._cities)
class CityIterator:
def __init__(self, city_obj):
# cities is an instance of Cities
self._city_obj = city_obj
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index >= len(self._city_obj):
raise StopIteration
else:
item = self._city_obj._cities[self._index]
self._index += 1
return itemNow we can create the iterator objects without having to recreate the Cities object every time.
But, we still have to remember to create a new iterator, and we can no longer iterate over the cities object anymore!
Iterables
Now we finally come to how an iterable is defined in Python.
An iterable is an object that:
implements the
__iter__methodand that method returns an iterator which can be used to iterate over the object
Now we can put the iterator class inside our
Citiesclass to keep the code self-contained:
Since our Cities could also be a sequence, we could also decide to implement the __getitem__ method to make it into a sequence:
It's a sequence, also an iterable
Python Built-In Iterables and Iterators
Last updated
Was this helpful?
