Looking at the next element in a for loop

Peter Otten __peter__ at web.de
Sun May 2 07:24:09 EDT 2004


- wrote:

> If I have a simple for loop like this:
> 
> for a in b:
>    print a
> 
> Is there a way I can get the next element in the loop? Something like
> this:
> 
> for a in b:
>    if a == 1:
>       print <next a>

You could reverse the logic:

>>> wasMatch = False
>>> for a in [1,2,1,1,1,3,1,4]:
...     if wasMatch: print a,
...     wasMatch = a == 1
...
2 1 1 3 4
>>>

Or do something like this:

>>> b = [1,2,1,1,1,3,1,4]
>>> for a, nexta in zip(b, b[1:]):
...     if a == 1: print nexta,
...
2 1 1 3 4
>>>

If you like the latter, you can use the window() function on the itertools
example page http://www.python.org/doc/current/lib/itertools-example.html
for a better implementation:

for a, nexta in window(b):
    if a == 1: print nexta,

Peter




More information about the Python-list mailing list