Last iteration?
Diez B. Roggisch
deets at nospam.web.de
Fri Oct 12 07:42:58 EDT 2007
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
>
>
> Can this be acomplished somehow?
def last_iter(iterable):
it = iter(iterable)
buffer = [it.next()]
for i in it:
buffer.append(i)
old, buffer = buffer[0], buffer[1:]
yield False, old
yield True, buffer[0]
for last, i in last_iter(xrange(4)):
if last:
print i*i
else:
print i
Diez
More information about the Python-list
mailing list