Skip to content

Instantly share code, notes, and snippets.

@hfs
Forked from mortenpi/pcniter.py
Created January 30, 2018 15:52
Show Gist options
  • Save hfs/d1ff165a24de796c8f78085441119012 to your computer and use it in GitHub Desktop.
Save hfs/d1ff165a24de796c8f78085441119012 to your computer and use it in GitHub Desktop.
Previous / current / next iterator in Python 3
def previous_current_next(iterable):
"""Make an iterator that yields an (previous, current, next) tuple per element.
Returns None if the value does not make sense (i.e. previous before
first and next after last).
"""
iterable=iter(iterable)
prv = None
try:
cur = next(iterable)
except StopIteration:
return
try:
while True:
nxt = next(iterable)
yield (prv,cur,nxt)
prv = cur
cur = nxt
except StopIteration:
yield (prv,cur,None)
# Examples
print(list(previous_current_next([])))
print(list(previous_current_next([1])))
print(list(previous_current_next([1,2])))
print(list(previous_current_next([1,2,3])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment