Accessing next/prev element while for looping

Nick Craig-Wood nick at craig-wood.com
Sun Dec 18 07:30:06 EST 2005


Joseph Garvin <k04jg02 at kzoo.edu> wrote:
>  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 think you'll find python lists are actually arrays not linked
lists...

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

Boundary conditions are a perenial problem in this sort of thing, what
to do at the start / end of the list...

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

I suppose you could use itertools...

>>> from itertools import *
>>> L=range(10)
>>> (L1, L2, L3) = tee(L, 3)
>>> L2.next()
0
>>> L3.next()
0
>>> L3.next()
1
>>> for prev, current, next in izip(L1, L2, L3): print prev, current, next
... 
0 1 2
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
>>> 

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list