Skip to content

Instantly share code, notes, and snippets.

@mortenpi
Created March 17, 2014 17:41
Show Gist options
  • Save mortenpi/9604377 to your computer and use it in GitHub Desktop.
Save mortenpi/9604377 to your computer and use it in GitHub Desktop.
Previous / current / next iterator in Python
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
cur = iterable.next()
try:
while True:
nxt = iterable.next()
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]))
Copy link

ghost commented Oct 12, 2020

how about just add prev and current as keywords to compliment next

@Kristine1975
Copy link

In Python 3.5 you can also use next(iterable).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment