Newbie: last item of a loop

Gerhard Häring gh at ghaering.de
Fri May 2 08:18:17 EDT 2003


Sven Brandt wrote:
> Hi,
> 
> to those familiar with Zope:
> Is there an equivalent the the tag variable of dtml-in 'sequence-end'?
> 
> In "python-speak":
> how do I determin that the current item in a for loop is the last 
> (first) item of a sequence?
> 
> Is there a more efficiant (in terms of cpu-resources) way than:
> 
> for i in my_sequence:
>   if i.index < len(my_sequenec):
>   print "Last item!"

If you want to treat the last item differently from the rest of the 
sequence, then I'd suggest explicitely doing so:

for item in seq[:-1]:
     # do stuff

# do stuff with seq[-1]

If these slices are unfamiliar to you, you can look them up in the 
Python docs.

-- Gerhard





More information about the Python-list mailing list