Solution 1

class ListIterator(object):
    def __init__(self, elems):
        self.elems = elems
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.index >= len(self.elems):
            raise StopIteration()

        elem = self.elems[self.index]
        self.index += 1

        return elem

    next = __next__

List Iterator

The objective of this assignment is to build a simple ListIterator that receives a list and its only purpose is to iterate it. It's silly and not really useful, but the idea is to reinforce on the iteration methods. Example of usage:

for elem in ListIterator([5, 4, 3, 2, 1]):

>>> 5

The code in the editor has some sample code that you can uncomment and use the RUN CODE button to try out.

Test Cases

test with empty list - Run Test

import pytest

def test_with_empty_list():
    it = iter(ListIterator([]))
    with pytest.raises(StopIteration):

test with elements - Run Test

import pytest

def test_with_elements():
    it = iter(ListIterator(['a', 'b', 'c']))

    assert next(it) == 'a'
    assert next(it) == 'b'
    assert next(it) == 'c'

    with pytest.raises(StopIteration):
class ListIterator(object): pass # for elem in ListIterator([3, 2, 1]): # print(elem)