Last active
August 29, 2015 14:26
-
-
Save openrijal/674a874591a78f6656e0 to your computer and use it in GitHub Desktop.
Get Previous and Next items in a forloop in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
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