How to detect the last element in a for loop

Tom Verbeure tom.verbeure at verizon.no.sp.am.net
Sun Jul 28 09:16:48 EDT 2002


> 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...

>  > Given that you have an explicit iterator, wouldn't it be trivial to
> add an
>  > 'end()' method to this iterator to indicate the end of the sequence
> (just
>  > like C++ iterators) ?
>  >
>  > This would result in:
>  >
>  > for item in iterator:
>  >     if iterator.next().end():
>  >         do_something_special
>  >
>  >     do_something_for_all
> 
> I think you've misunderstood the end() value in C++ STL iterators.  It
> is not the last item, but one past the last item.  The iterator can take
> the end value, but dereferencing the end value is illegal.

That would be the case if I would check for iterator.end(), but I check for 
iterator.next().end() !

Tom






More information about the Python-list mailing list