Skip to content

Instantly share code, notes, and snippets.

@openrijal
Last active August 29, 2015 14:26
Show Gist options
  • Save openrijal/674a874591a78f6656e0 to your computer and use it in GitHub Desktop.
Save openrijal/674a874591a78f6656e0 to your computer and use it in GitHub Desktop.
Get Previous and Next items in a forloop in Python
'''
source: http://stackoverflow.com/a/1012089/1777024
'''
from itertools import tee, islice, chain, izip # official documentation https://docs.python.org/2/library/itertools.html
def prev_and_next(my_iterable):
prevs, items, nexts = tee(my_iterable, 3)
prevs = chain([None], prevs)
nexts = chain(islice(nexts, 1, None), [None])
return izip(prevs, items, nexts)
my_iterable = ['one', 'two', 'three', 'four', 'five']
for previous, item, nxt in prev_and_next(my_iterable):
print "Previous item is: " , previous , "--" , "Current item is: " , item , "--" , "Next item is: ", nxt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment