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


Groups > comp.lang.python > #13151

Re: Idioms combining 'next(items)' and 'for item in items:'

References <j4gea4$m3b$1@dough.gmane.org> <CALwzidkeRA69p+Vw80xnE_sndx64zr2yXQsFZhS520KYbjxTxA@mail.gmail.com> <j4iomc$te4$1@dough.gmane.org>
Date 2011-09-12 08:41 +1000
Subject Re: Idioms combining 'next(items)' and 'for item in items:'
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1009.1315780869.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Sep 12, 2011 at 2:47 AM, Terry Reedy <tjreedy@udel.edu> wrote:
> What you are saying is a) that the following code
>
> for title in ['amazinG', 'a helL of a fiGHT', '', 'igNordEd']:
>    print(fix_title(title))
>

At least in Python 3.2, this isn't the case. StopIteration breaks the
loop only if it's raised during the assignment, not during the body.

>>> x=iter([1,2,3,4,5])
>>> for i in x:
	print("%d - %d"%(i,next(x)))

1 - 2
3 - 4
Traceback (most recent call last):
  File "<pyshell#281>", line 2, in <module>
    print("%d - %d"%(i,next(x)))
StopIteration

Compare with:

>>> def pair(it):
	while True:
		yield next(it),next(it)

>>> x=iter([1,2,3,4,5])
>>> for i,j in pair(x):
	print("%d - %d"%(i,j))

1 - 2
3 - 4

In this case, the StopIteration bubbles up and quietly terminates the loop.

ChrisA

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


Thread

Re: Idioms combining 'next(items)' and 'for item in items:' Chris Angelico <rosuav@gmail.com> - 2011-09-12 08:41 +1000

csiph-web