In Python…
I have a nested list defined in a class as:
self.env = [[ None for i in range(columnCount)] for j in range(rowCount) ]
For the purpose of this question, lets assume this nested list contained values of:
[None, None, None, None]
[None, None, None, None]
[None, None, 0, None]
[None, None, None, None]
I need to be able to leverage the iter and next() methods to go through this list in column major order (row0,col0 row1,col0, row2,col0…).
The intent is for it to send the value located in that grid location to another function to get processed.
So far I have the iter function defined as:
def __iter__(self):
return iter(self.env)
Then I have the next function defined as:
def next(self):
self.currentRow += 1
self.currentColumn += 1
if ( (self.currentRow < self.getRowCount()) and (self.currentColumn < self.getColumnCount()) ):
return self.env[self.currentRow][self.currentColumn]
else:
raise StopIteration
The problem I am having is that it seems the iter function is return each row as a list, but it is not making a call to the next method to further process that list.
My objective is to get print the values at each grid location invdividually… as in:
None
None
…
None
0
None
…
None
Can someone elaborate on what it is I am missing in order to accomplish this?
Your
__iter__function is returningiter(self.env), which returns the iterator for self.env. If you want your next method to be called,__iter__, you should returnself. But there are other issues in your implementation, for example, your iterator won’t work more than once.There are easier ways to achieve this. You can write a Generator Expression/List Comprehensions to achieve this (see @Eric’s answer). You can also write a generator method. E.g.: