__next__ and StopIteration

Ethan Furman ethan at stoneleaf.us
Tue Feb 10 11:44:39 EST 2015


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.

--
~Ethan~

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20150210/db5b5bb5/attachment.sig>


More information about the Python-list mailing list