__next__ and StopIteration

Ethan Furman ethan at stoneleaf.us
Tue Feb 10 12:33:23 EST 2015


On 02/10/2015 08:53 AM, Ian Kelly wrote:
> 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.

Cool, thanks for the correction.

--
~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/1ac47a58/attachment.sig>


More information about the Python-list mailing list