logo

Programming Languages - Iterators

Python

an iterator implements the methods __iter__() and __next__().

To get an iterator from an iterable container (lists, tuples, dictionaries, and sets), call iter().

Call next() to get the next value of the iterator.

t = ("a", "b", "c")
i = iter(t)

print(next(i)) # a
print(next(i)) # b
print(next(i)) # c

In a loop:

iterator = get_iterator()
for x in iterator:
    print(x)

Reverse:

def reverse(data):
    for index in range(len(data) - 1, -1, -1):
        yield data[index]

use for ... in ...

>>> list(reversed('golf'))
['f', 'l', 'o', 'g']
class Reverse:
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def next(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]
>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
>>> for char in rev:
...     print char
...
m
a
p
s