How to detect the last element in a for loop

Andreas Kostyrka andreas at kostyrka.priv.at
Tue Jul 30 16:41:00 EDT 2002


Am Son, 2002-07-28 um 08.00 schrieb Bryan Olson:
> 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])
Breaks on myList=[]
Better:
for a in myList[:-1]:
	do_stuff(a)
for a in myList[-1:]:
	special_stuff(a)

That works, because slicing an empty list always returns an empty list,
while accessing an nonexistant element throws an exception. :)

Andreas





More information about the Python-list mailing list