Last iteration?
Paul Hankin
paul.hankin at gmail.com
Fri Oct 12 09:25:00 EDT 2007
On Oct 12, 2:18 pm, Carsten Haese <cars... at uniqsys.com> wrote:
> On Fri, 2007-10-12 at 12:58 +0200, Florian Lindner 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
>
> Here's another solution:
>
> mylist = [1,2,3]
> for j,i in reversed(list(enumerate(reversed(mylist)))):
> if j==0:
> print i*i
> else:
> print i
Nice! A more 'readable' version is:
mylist = [1,2,3]
for not_last, i in reversed(list(enumerate(reversed(mylist)))):
if not_last:
print i
else:
print i * i
--
Paul Hankin
More information about the Python-list
mailing list