Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #110786

Re: Iteration, while loop, and for loop

From Ian Kelly <ian.g.kelly@gmail.com>
Newsgroups comp.lang.python
Subject Re: Iteration, while loop, and for loop
Date 2016-06-29 09:29 -0600
Message-ID <mailman.114.1467214578.2358.python-list@python.org> (permalink)
References <079ff112-8f18-4a27-938f-12e4e55a4a5b@googlegroups.com> <577295b3$0$1598$c3e8da3$5496439d@news.astraweb.com> <20160628122308.4578d876@bigbox.christie.dr> <nkudsr$335$1@ger.gmane.org> <CALwzidkBztoyJY=VQu=BuFqVTU3XM0pXa_A+evYOeqGv-6jhbg@mail.gmail.com>

Show all headers | View raw


On Tue, Jun 28, 2016 at 11:58 AM, Grant Edwards
<grant.b.edwards@gmail.com> wrote:
> On 2016-06-28, Tim Chase <python.list@tim.thechases.com> wrote:
>> On 2016-06-29 01:20, Steven D'Aprano wrote:
>>> While loops are great for loops where you don't know how many
>>> iterations there will be but you do know that you want to keep
>>> going while some condition applies:
>>>
>>> while there is still work to be done:
>>>     do some more work
>>
>> I find this particularly the case when the thing being iterated over
>> can be changed, such as a queue of things to process:
>>
>>   items = deque()
>>   items.append(root_node)
>>   while items:
>>     item = items.popleft()
>>     process(item)
>>     items.extend(item.children)
>
> Yep, I often do something similar when processing a block of data
> bytes comprising a sequence of "things" of varying number of bytes.
>
>     data = read_a_blob_of_bytes()
>     while data:
>         #figure out how long the first "thing" is
>         len = <some expression typically involving the first few bytes of 'data'>
>         handle_thing(data[:len])
>         data = data[len:]
>> 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:

  def __init__(self, iterable):
    self._stopped = False
    self.replace(iterable)

  def __iter__(self):
    return self

  def __next__(self):
    if self._stopped:
      raise StopIteration
    while self._iterator or self._iterables:
      if self._iterator:
        try:
          return next(self._iterator)
        except StopIteration:
          self._iterator = None
      if self._iterables:
        self._iterator = iter(self._iterables.popleft())
    self._stopped = True
    raise StopIteration

  def clear():
    self._iterables.clear()
    self._iterator = None

  def replace(self, iterable):
    self._check_stopped()
    self._iterables = collections.deque([iterable])
    self._iterator = None

  def append(self, item):
    self.extend([item])

  def extend(self, iterable):
    self._check_stopped()
    self._iterables.append(iterable)

  def _check_stopped(self):
    if self._stopped:
      raise ValueError('Tried to mutate a stopped iterator')


# Example:

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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Iteration, while loop, and for loop Elizabeth Weiss <cake240@gmail.com> - 2016-06-28 05:36 -0700
  Re: Iteration, while loop, and for loop Michael Selik <michael.selik@gmail.com> - 2016-06-28 13:15 +0000
    Re: Iteration, while loop, and for loop BartC <bc@freeuk.com> - 2016-06-28 14:29 +0100
      Re: Iteration, while loop, and for loop Michael Selik <michael.selik@gmail.com> - 2016-06-28 13:58 +0000
      Re: Iteration, while loop, and for loop Lawrence D’Oliveiro <lawrencedo99@gmail.com> - 2016-06-28 22:58 -0700
  Re: Iteration, while loop, and for loop BartC <bc@freeuk.com> - 2016-06-28 14:24 +0100
  RE: Iteration, while loop, and for loop "Joseph Lee" <joseph.lee22590@gmail.com> - 2016-06-28 06:26 -0700
  Re: Iteration, while loop, and for loop Jussi Piitulainen <jussi.piitulainen@helsinki.fi> - 2016-06-28 16:42 +0300
  Re: Iteration, while loop, and for loop Michael Selik <michael.selik@gmail.com> - 2016-06-28 13:51 +0000
  Re: Iteration, while loop, and for loop Steven D'Aprano <steve@pearwood.info> - 2016-06-29 01:20 +1000
    Re: Iteration, while loop, and for loop Jussi Piitulainen <jussi.piitulainen@helsinki.fi> - 2016-06-28 18:28 +0300
    Re: Iteration, while loop, and for loop Tim Chase <python.list@tim.thechases.com> - 2016-06-28 12:23 -0500
    Re: Iteration, while loop, and for loop Grant Edwards <grant.b.edwards@gmail.com> - 2016-06-28 17:58 +0000
    Re: Iteration, while loop, and for loop Ian Kelly <ian.g.kelly@gmail.com> - 2016-06-29 09:29 -0600
      Re: Iteration, while loop, and for loop Steven D'Aprano <steve@pearwood.info> - 2016-06-30 09:59 +1000
        Re: Iteration, while loop, and for loop Tim Chase <python.list@tim.thechases.com> - 2016-06-30 05:44 -0500
        Re: Iteration, while loop, and for loop Ian Kelly <ian.g.kelly@gmail.com> - 2016-06-30 07:04 -0600
        Re: Iteration, while loop, and for loop Ian Kelly <ian.g.kelly@gmail.com> - 2016-06-30 07:10 -0600
        Re: Iteration, while loop, and for loop jfong@ms4.hinet.net - 2016-06-30 19:12 -0700
  Re: Iteration, while loop, and for loop Veek M <vek.m1234@gmail.com> - 2016-10-27 14:35 +0530

csiph-web