Last iteration?

Stefan Behnel stefan.behnel-n05pAM at web.de
Fri Oct 12 07:29:53 EDT 2007


Florian Lindner wrote:
> 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?

You could do this:

  l = [1,2,3]
  s = len(l) - 1
  for i, item in enumerate(l): # Py 2.4
      if i == s:
          print item*item
      else:
          print item

Or, you could look one step ahead:

   l = [1,2,3]
   next = l[0]
   for item in l[1:]:
       print next
       next = item
   print next * next

Stefan



More information about the Python-list mailing list