469,927 Members | 1,784 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,927 developers. It's quick & easy.

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>
Jul 18 '05 #1
2 1477
ma***********@hotmail.com (-) writes:
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[i] is 1:
print b[i+1]
Jul 18 '05 #2
- 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/li...s-example.html
for a better implementation:

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

Peter

Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by Brian Burgess | last post: by
13 posts views Thread by Joseph Garvin | last post: by
13 posts views Thread by andreas | last post: by
4 posts views Thread by Neo | last post: by
11 posts views Thread by magicman | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.