Looking at the next element in a for loop

?

-

Hi,

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

Tor Iver Wilhelmsen

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>

No, not as long as you use an iterator. If you use an index instead,
it's easy of course.

for i in xrange(len(b)):
if b is 1:
print b[i+1]
 
P

Peter Otten

- said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,196
Messages
2,571,036
Members
47,631
Latest member
kukuh

Latest Threads

Top