How to catch StopIteration?

Lie Lie.1296 at gmail.com
Tue Jun 17 01:36:07 EDT 2008


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?
>
> def collatz(n):
>   r=[]
>   while n>1:
>     r.append(n)
>     n = 3*n+1 if n%2 else n/2
>     yield r
>
> for i, x in enumerate(collatz(13)):
>   try:
>     last = x[:i+1]
>     print x[:i+1]
>   except StopIteration:
>     print last.appnd(1)
>
> Output:
> [13]
> [13, 40]
> [13, 40, 20]
> [13, 40, 20, 10]
> [13, 40, 20, 10, 5]
> [13, 40, 20, 10, 5, 16]
> [13, 40, 20, 10, 5, 16, 8]
> [13, 40, 20, 10, 5, 16, 8, 4]
> [13, 40, 20, 10, 5, 16, 8, 4, 2]
> last.appnd(1) <= [13, 40, 20, 10, 5, 16, 8, 4, 2, 1]  # i want this
> list

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)

def collatz(n):
  r=[]
  while n>1:
    r.append(n)
    n = 3*n+1 if n%2 else n/2
    yield r

for i, x in enumerate(collatz(13)):
    last = x[:i+1]
    print x[:i+1]
last.append(1)
print last

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



More information about the Python-list mailing list