Fix memory leaks from the previous commit

The code now follows the Iterator Protocol
(https://docs.python.org/2/c-api/iter.html).