How to detect the last element in a for loop

John Hunter jdhunter at nitace.bsd.uchicago.edu
Sun Jul 28 11:49:56 EDT 2002


>>>>> "Tom" == Tom Verbeure <tom.verbeure at verizon.no.sp.am.net> writes:

    Tom> Hello All,

    Tom> I often have the case where I need to loop through a bunch of
    Tom> elements, but do something special on for the last line of
    Tom> code.


What about the good, old fashioned index?  To my eyes, it is very
readable 

N = len(seq):
for i in range(N):
   do_something(seq[i])
   if i==someVal: 
      do_something_else(seq[i])  

It's not really that god awful is it? 

Also, for the example you posted, you can use string.join....

import string
seq = range(10)
s =  string.join(map(str, seq), ', ')

Cheers,
John Hunter
 



More information about the Python-list mailing list