How to detect the last element in a for loop

Fredrik Lundh fredrik at pythonware.com
Sun Jul 28 11:02:16 EDT 2002


Tom Verbeure wrote:

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

so why not just change the for loop?

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

for extra style points, you can use the else statement to
make sure the special stuff isn't done if you have to break
out of the loop:

    for a in myList:
        do_stuff(a)
    else:
        special_stuff(a)

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

as the code in my earlier post tried to tell you, iterator.next()
returns the next item from the sequence, or raises an exception.

to implement your proposal, *all* objects need to implement an
end method, which should return true if they are the last object
in a container.  since objects can be shared (the containers only
hold references), and objects don't know or care about what
containers they are in today, that's pretty much means that
we have to start over from scratch...

</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->






More information about the Python-list mailing list