Idioms combining 'next(items)' and 'for item in items:'
Chris Angelico
rosuav at gmail.com
Sun Sep 11 18:41:05 EDT 2011
On Mon, Sep 12, 2011 at 2:47 AM, Terry Reedy <tjreedy at 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
More information about the Python-list
mailing list