How to catch StopIteration?

Lie Lie.1296 at gmail.com
Tue Jun 17 08:10:01 CEST 2008


On Jun 17, 12:36 pm, Lie <Lie.1... at gmail.com> wrote:
> On Jun 17, 10:50 am, ccy56... at gmail.com wrote:
>
>
>
> > I'm writing to see calcuration process.
> > And so, I can't catch StopIteration...
>
> > What is mistake?
>
(snip)
>
> In a for-loop, StopIteration is caught by the for-loop for your
> convenience (so you don't need to set up try-except of your own)
(snip)

To clarify, when the for-loop catches StopIteration, the for-loop
quits and stop looping, continuing to the next statement after the
loop block.

To be more accurate, in your case, the StopIteration is caught by the
enumerate() when it is enumerating collatz. The for-loop then loops
the generator expression returned by enumerate, when enumerate runs
out of things to return (i.e. when enumerate caught StopIteration
raised by collatz), enumerate raise StopIteration which is caught by
the for-loop.

> PS: btw, you can't write 'print last.append(1)' because list
> operations like append doesn't return itself.

To clarify, list append returns 'None' which, in python, means it is a
method/sub. In actuality, python doesn't recognize the difference
between method and function.



More information about the Python-list mailing list