Accessing next/prev element while for looping

Joseph Garvin k04jg02 at kzoo.edu
Sun Dec 18 06:23:21 EST 2005


When I first came to Python I did a lot of C style loops like this:

for i in range(len(myarray)):
    print myarray[i]

Obviously the more pythonic way is:

for i in my array:
    print i

The python way is much more succinct. But a lot of times I'll be looping 
through something, and if a certain condition is met, need to access the 
previous or the next element in the array before continuing iterating. I 
don't see any elegant way to do this other than to switch back to the C 
style loop and refer to myarray[i-1] and myarray[i+1], which seems 
incredibly silly given that python lists under the hood are linked 
lists, presumably having previous/next pointers although I haven't 
looked at the interpeter source.

I could also enumerate:

for i, j in enumerate(myarray):
    print myarray[i], j # Prints each element twice

And this way I can keep referring to j instead of myarray[i], but I'm 
still forced to use myarray[i-1] and myarray[i+1] to refer to the 
previous and next elements. Being able to do j.prev, j.next seems more 
intuitive.

Is there some other builtin somewhere that provides better functionality 
that I'm missing?



More information about the Python-list mailing list