Is there an easy way to get next and prev values in a for-loop?

for-loop, iteration, python

Solution

Here is a common pattern that I use to iterate over pairs of items in a sequence:

>>> a = range(10)
>>> for i, j in zip(a, a[1:]):
...  print i, j
... 
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9

If you want three items (prev, item, next) you can do this:

>>> for i, j, k in zip(a, a[1:], a[2:]):
...  print i, j, k
... 
0 1 2
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9

`i` is the previous element, `j` is the current element, `k` is the next element.

Of course, this "starts" at 1 and "ends" at 8. What should you receive as prev/next at the ends? Perhaps `None`? Probably easiest to just do this:

>>> a = [None] + a + [None]
>>> for i, j, k in zip(a, a[1:], a[2:]):
...  print i, j, k
... 
None 0 1
0 1 2
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
8 9 None

Problem

So...is there an easy way to get next and previous values while iterating with a for-loop in Python? I know this can be easily done if you do something like: ``` a = [3,4,5,6,3,4,5] for x in range(len(a)): next = a[x+1] ``` But what about: ``` for x in a: x.next?? ```

Original source