How to detect the last element in a for loop

Terry Reedy tjreedy at udel.edu
Sat Jul 27 16:45:30 EDT 2002


"Tom Verbeure" <tom.verbeure at verizon.no.sp.am.net> wrote in message
news:shD09.10086$9U4.6939 at nwrddc01.gnilink.net...
>
> Hello All,
>
> I often have the case where I need to loop through a bunch of
elements, but
> do something special on for the last line of code.

>     first = 1
>     for port in self.portDefsList:
>         if first == 0:
>             string += ", "
>         else:
>             first = 0
>         string += str(port)
>         pass

You actually special case the first item.  However, you really want
the string join method:

result = ', '.join(map(str, self.portDefsList))

Terry J. Reedy






More information about the Python-list mailing list