Last iteration?

Paul Hankin paul.hankin at gmail.com
Fri Oct 12 14:04:30 CEST 2007


On Oct 12, 11:58 am, Florian Lindner <Florian.Lind... at xgm.de> wrote:
> Hello,
> can I determine somehow if the iteration on a list of values is the last
> iteration?
>
> Example:
>
> for i in [1, 2, 3]:
>    if last_iteration:
>       print i*i
>    else:
>       print i

Yes, either use enumerate or just stop the loop early and deal with
the last element outside the loop.

xs = [1, 2, 3]
for x in xs[:-1]:
    print x
print xs[-1] * xs[-1]

--
Paul Hankin




More information about the Python-list mailing list