How to detect the last element in a for loop

Christopher A. Craig list-python at ccraig.org
Mon Jul 29 00:52:06 EDT 2002


Tom Verbeure <tom.verbeure at verizon.no.sp.am.net> writes:

> 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 do not think it means what you think it means:

>>> iterator = iter([0,1,2,3])
>>> for i in iterator:
...   if iterator.next(): pass
...   print i
0
2

As you see, iterator.next() moves iterator to the next item, which
means that even if you had a .end() method (which you don't), you
couldn't use it like this.

One way you could do this (another, better, way to do it is in another
post, but only works if you know the length at the beginning) is to
always track the next item:

next = iterator.next()
while next:
  this=next
  try: 
     next=iterator.next()
  except StopIteration:
     next=False
     do_something_special
  do_something_for_all


-- 
Christopher A. Craig <list-python at ccraig.org>
"640K ought to be enough for anybody." Bill Gates




More information about the Python-list mailing list