Iteration, while loop, and for loop

Tim Chase python.list at tim.thechases.com
Thu Jun 30 06:44:59 EDT 2016


On 2016-06-30 09:59, Steven D'Aprano wrote:
> 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;  

Convenient to know.  I was fairly certain that this had failed for me
in past versions, but I went back to the oldest I have (2.4) and it
still works there.  Might have to revisit some queuing code I have.

That said, it's not consistent across iterable container types.  With

  mi = set('bananas')
  for char in mi:
    if char == 'a':
      mi.add('X')
    print(char)
  else:
    print()

I get

  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  RuntimeError: Set changed size during iteration

If the list() meets your needs, then you're in luck.  But just as
frequently, I want to use a set() or a dict() and have to write my
own wrapper around it.

-tkc




More information about the Python-list mailing list