Last iteration?

Robin Kåveland kaaveland at gmail.com
Sat Oct 13 07:50:02 EDT 2007


On Oct 12, 12:58 pm, 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
>
> that would print
>
> 1
> 2
> 9
>
> Can this be acomplished somehow?
>
> Thanks,
>
> Florian


If you want to do this over a list or a string, I'd just do:

for element in iterable[:-1]: print iterable
print iterable[-1]  * iterable[-1]

No need for it to get more advanced than that :)




More information about the Python-list mailing list