By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,923 Members | 1,655 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,923 IT Pros & Developers. It's quick & easy.

Looking at the next element in a for loop

P: n/a
-
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
- 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.