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


Groups > comp.lang.python > #110786

Re: Iteration, while loop, and for loop

Path csiph.com!news.freedyn.net!newsreader4.netcologne.de!news.netcologne.de!fu-berlin.de!uni-berlin.de!not-for-mail
From Ian Kelly <ian.g.kelly@gmail.com>
Newsgroups comp.lang.python
Subject Re: Iteration, while loop, and for loop
Date Wed, 29 Jun 2016 09:29:18 -0600
Lines 93
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>
Mime-Version 1.0
Content-Type text/plain; charset=UTF-8
X-Trace news.uni-berlin.de SiC4Hc4H2yk9EdDrsdtbCwMM3Nht4D1mhZ5A3qcEWudQ==
Return-Path <ian.g.kelly@gmail.com>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.004
X-Spam-Evidence '*H*': 0.99; '*S*': 0.00; 'bytes.': 0.07; 'data:': 0.07; 'collections': 0.09; 'subject:while': 0.09; 'example:': 0.10; ':-)': 0.12; 'def': 0.13; 'things.': 0.15; '"for"': 0.16; '"while"': 0.16; '2016': 0.16; 'item):': 0.16; 'iterated': 0.16; 'len': 0.16; 'loops': 0.16; 'pythonic': 0.16; 'received:io': 0.16; 'received:psf.io': 0.16; 'wrote:': 0.16; 'bytes': 0.18; 'char': 0.18; 'try:': 0.18; '>>>': 0.20; 'am,': 0.23; 'seems': 0.23; 'import': 0.24; 'tim': 0.24; 'header:In-Reply-To:1': 0.24; 'skip:_ 20': 0.26; 'message-id:@mail.gmail.com': 0.27; 'sequence': 0.27; 'chase': 0.29; 'queue': 0.29; 'yields': 0.29; 'raise': 0.29; 'skip:s 30': 0.31; 'skip:_ 10': 0.32; 'class': 0.33; "d'aprano": 0.33; 'steven': 0.33; 'wrap': 0.33; 'similar': 0.33; 'tue,': 0.34; 'except': 0.34; 'that,': 0.34; 'received:google.com': 0.35; 'false': 0.35; 'stopped': 0.35; 'something': 0.35; 'item': 0.35; 'but': 0.36; 'skip:i 20': 0.36; 'there': 0.36; 'to:addr:python- list': 0.36; 'subject:: ': 0.37; 'being': 0.37; 'things': 0.38; 'self': 0.38; 'data': 0.39; 'to:addr:python.org': 0.40; 'where': 0.40; 'still': 0.40; 'some': 0.40; 'your': 0.60; 'telling': 0.61; 'more': 0.63; 'great': 0.63; 'here': 0.66; 'bananas': 0.84; 'done:': 0.84; 'to:name:python': 0.84; 'edwards': 0.91
DKIM-Signature v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=mime-version:in-reply-to:references:from:date:message-id:subject:to; bh=SYwvBujHNUwJYmA2Di34UblthfuOi38Ht0JdX0/tgoM=; b=QxiTbd7r6RbaKpi/ptkhSQ2JKdcjCUerOjGEupy1ACKNHxIzmo0b/bQ2qRA0a4ytGs P4jzgENVUf13N6hp7OftBazFao5eqGKDnXKCwIXgnZA0dpX24WL8RBfj6P7x7J3EYIOe OsZuIakvckSg02+pkbWhu4hHWbDXzChiEDXbs0O2FA1sH4wwmHcOn/ti/el0ygoE+2nM 7RRMGcR3u4UCW6XvMYOf/sBwAFsgISNBTTVOacKaILdfWrT5rufheEcGt4GuhX1hIndv RbkEp3WkV/uy+o1L/zPy0cu1ON9gOB+89ujSBJ8wCMPUmuk3m6SX/GBEW3PNRz63w1ia 6Q3w==
X-Google-DKIM-Signature v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20130820; h=x-gm-message-state:mime-version:in-reply-to:references:from:date :message-id:subject:to; bh=SYwvBujHNUwJYmA2Di34UblthfuOi38Ht0JdX0/tgoM=; b=GvHof8OWBIM/tEhVwg3CpU3Wi3QOAOWLMRuyLVvt5IOqGX+SNtakztlOoxtrXo7ylu +/nr37bs/YYgNPUc9lVKSsErCt4C4b9CNH53uKuAuTpXR3HWW8pOinYdNGtxZvUiilag b52/k0OoIQwEIisdrOZXXeJ+x6rihQPAF0Nx//MEphaAYxqTp6vvPgTcJIjzaZdTaaxx ecq3rwelK/3xaXs3LfF/18VQc+74Q/k8zTHk3wWXsDTTnAekAtgrSVihh4d+YUeOUCUJ LhTBld3CxJ5ix9mkh0MIHs+5aQzSQCogl363kXg9I1ZlYB1hsb+2l1H2/YsbpYIw1w8N e6Ag==
X-Gm-Message-State ALyK8tLnHUMLEoHHMdGDjc+4fRpnLTKgG+F8N9ETT2//u509txaNrVKDIgV1075B0o9zKr8kzkoL+z24zvqciQ==
X-Received by 10.157.25.170 with SMTP id k39mr6765921otk.86.1467214197557; Wed, 29 Jun 2016 08:29:57 -0700 (PDT)
In-Reply-To <nkudsr$335$1@ger.gmane.org>
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.22
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <https://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list/>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <https://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
X-Mailman-Original-Message-ID <CALwzidkBztoyJY=VQu=BuFqVTU3XM0pXa_A+evYOeqGv-6jhbg@mail.gmail.com>
X-Mailman-Original-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>
Xref csiph.com comp.lang.python:110786

Show key headers only | 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