I want to have an iterator, which essentially returns each element of a list attribute. The code below works, but requires an ugly instance variable causing problems:
As soon as I create another iterator instance (instead of re-using testIter) the nested loop works fine, but this does not seem an option for my full-life problem.
How can I get rid of the instance variable without sacrificing the neat for something in syntax?
class MyIterator(object):
def __init__(self, myList):
self._list = myList
def __iter__(self):
self.cursor = 0
return self
def next(self):
try:
nextElem = self._list[self.cursor]
except IndexError:
raise StopIteration
else:
self.cursor += 1
return nextElem
def test(l):
testIter = MyIterator(l)
for line in testIter:
for column in testIter:
print "{}/{}".format(line, column),
print
if __name__ == "__main__":
test("abc")