[Tutor] Skipping elements from inside generator loops
alan.gauld@bt.com
alan.gauld@bt.com
Fri, 2 Aug 2002 15:02:46 +0100
> ... I find that you can not do this with "normal" for loops:
>
> ===============================
> for a in range(len(procession)):
> if procession[a] == 'ALARM!':
> a = a+1
> else:
> print procession[a]
> ===============================
This has nothing to do with the processing of the
list, just how the value of a is assigned.
for a in range(len...) creates a line like:
for a in [0,1,2,3,...,<lenth-1>]
your a = a+1 changes a inside the loop but when it
comes round to the beginning a is set to the next
value in the list regardless of what you have set
it to.
Instead try deleting the a+1 element from the list,
that will be closer. The only snag there is that
you will now run off the end of the list because it
doesn't correspond to the original length! Bad idea.
Alternative technique is to use a while loop and
manually maintain the list length. generators etc
provide a nicer way of dealing with these kinds of
issue.
Alan G