__next__ and StopIteration
Ian Kelly
ian.g.kelly at gmail.com
Tue Feb 10 11:53:57 EST 2015
On Tue, Feb 10, 2015 at 9:44 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 02/09/2015 08:46 PM, Chris Angelico wrote:
>>
>> class Grid:
>> blah blah
>>
>> def __iter__(self):
>> for row in range(self._rows):
>> for col in range(self._cols):
>> if self._grid[row][col]:
>> yield self._grid[row][col]
>
> I strongly suggest you remove the
>
> if self._grid[row][col]:
>
> line.
>
> Best case scenario: the entire grid is blank, and iterating through it does nothing.
>
> Worst case scenario: only some elements evaluate as False, so your loop doesn't execute the full number of times; i.e.
> with a grid of 4x5 with 7 blank cells you get 13 iterations -- probably not what was expected.
Depends on what the expected behavior is -- is every grid position
something that should be included in the iteration, or are we looking
at elements of a container where some possible locations may be empty?
You don't expect a dict iteration to yield empty buckets, for example.
I have some code that looks similar to this, which is an iterator for
a chess board that yields the contained pieces. It doesn't really make
sense in that case to yield empty squares.
More information about the Python-list
mailing list