How to detect the last element in a for loop

Tom Verbeure tom.verbeure at verizon.no.sp.am.net
Sat Jul 27 16:21:44 EDT 2002


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. 

Currently, I can solve it this way:

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

This works fine, but it introduces an extra variable. Is there a cleaner 
way to do this?

Thanks,
Tom

 



More information about the Python-list mailing list