Iteration, while loop, and for loop

Steven D'Aprano steve at pearwood.info
Wed Jun 29 19:59:27 EDT 2016


On Thu, 30 Jun 2016 01:29 am, Ian Kelly wrote:

> On Tue, Jun 28, 2016 at 11:58 AM, Grant Edwards
> <grant.b.edwards at gmail.com> wrote:
[...]
>>> But then, if you wrap up your "while" loop as a generator that yields
>>> things, you can then use it in a "for" loop which seems to me like
>>> the Pythonic way to do things. :-)
>>
>> Yea, I keep telling myself that, but I never actually do it.
> 
> Here you go:
> 
> import collections
> 
> class MutableIterator:
[snip 8 methods and 33 lines of code]

> # Example:
> 
>>>> mi = MutableIterator('bananas')
>>>> for char in mi:
> ...   if char == 'a':
> ...     mi.extend(' yum')
> ...   print(char, end='')
> ...
> bananas yum yum yum

I'm curious what REPL you are using, because in the vanilla Python
interactive interpreter, the output if over-written by the prompt. That is,
what I see in Python 3.6 is:

py> nas yum yum yumpy> 

unless I take steps to prevent that. See below.


But there's no need to go to such effort for a mutable iterator. This is
much simpler:

py> mi = list('bananas')
py> for char in mi:
...     if char == 'a':
...             mi.extend(' yum')
...     print(char, end='')
... else:  # oh no, the feared for...else!
...     # needed to prevent the prompt overwriting the output
...     print()
...
bananas yum yum yum
py> 


This example shows two things:

(1) There's no need for a MutableIterator, we have list;

(2) Anyone who says that for...else without break is useless is wrong.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.



More information about the Python-list mailing list