How to access the previous/next element in a for loop?
Expressed as a generator function:
def neighborhood(iterable):
iterator = iter(iterable)
prev_item = None
current_item = next(iterator) # throws StopIteration if empty.
for next_item in iterator:
yield (prev_item, current_item, next_item)
prev_item = current_item
current_item = next_item
yield (prev_item, current_item, None)
Usage:
for prev,item,next in neighborhood(l):
print prev, item, next
l = [1, 2, 3]
for i, j in zip(l, l[1:]):
print(i, j)