How to detect the last element in a for loop

Andrae Muys amuys at shortech.com.au
Sun Jul 28 20:18:37 EDT 2002


Tom Verbeure <tom.verbeure at verizon.no.sp.am.net> wrote in message news:<49S09.13011$9U4.7618 at nwrddc01.gnilink.net>...
> > For a simple solution, how about:
> > 
> > for a in myList[:-1]:
> >      do_stuff(a)
> > special_stuff(myList[-1])
> 
> No, I still want to do 'do_stuff' for the last element also. This may be, 
> say, 10 lines of code. Too much to duplicate it outside the loop, not 
> enough for a separate function...
> 

Now this comment I find strange, as personally I consider 10 lines of
code about the perfect length for a function.  If your functions are
consise they become self documenting.  As an added bonus, similar
functions appearing in different sections (often unrelated) of code,
can often suggest powerful abstractions that can make your code more
flexible and more maintainable.  I personally prefer a function to do
one thing.  If I find myself needing more then 15-20 lines to describe
'one thing' I stop and ask myself why I'm having so much trouble
describing 'one thing' consisely.  Is the function actually doing
multiple things?  Do I really understand what the functions trying to
do?  Am I trying to use the wrong programmign-paradigm to describe
'one thing'?  Maybe the function's in the wrong place, and working too
hard to obtain the data it needs?  Whatever the problem, I find a
function of >20 lines a symptom that there is something wrong.

5-10 lines + error handling. 

that's-my-general-target-ly yours

Andrae Muys



More information about the Python-list mailing list