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


Groups > comp.lang.python > #13151 > unrolled thread

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

Started byChris Angelico <rosuav@gmail.com>
First post2011-09-12 08:41 +1000
Last post2011-09-12 08:41 +1000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

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

FromChris Angelico <rosuav@gmail.com>
Date2011-09-12 08:41 +1000
SubjectRe: Idioms combining 'next(items)' and 'for item in items:'
Message-ID<mailman.1009.1315780869.27778.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web