How to detect the last element in a for loop

Bryan Olson fakeaddress at nowhere.org
Sun Jul 28 02:00:43 EDT 2002


Tom Verbeure wrote:
[...]
 > I am not familiar with iterators as objects in Python. I understand that
 >
 >     for a in myList:
 >         ...
 >
 > will result in an implicit iterator on myList.

For a simple solution, how about:

for a in myList[:-1]:
     do_stuff(a)
special_stuff(myList[-1])


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


--Bryan




More information about the Python-list mailing list