Previous and next values inside a loop https://stackoverflow.com/questions/1011938/python-previous-and-next-values-inside-a-loop/1012089#1012089
from itertools import tee, islice as slice, chain, izip as zip
def previous_and_next(iterable, fill_value=None):
prevs, items, nexts = tee(iterable, 3)
prevs = chain([fill_value], prevs)
nexts = chain(slice(nexts, 1, None), [fill_value])
return zip(prevs, items, nexts)