Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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]))
@Raki22

This comment has been minimized.

Copy link

Raki22 commented Jul 1, 2019

that is so useful Sir thank you so much :)

@ozcan-durak

This comment has been minimized.

Copy link

ozcan-durak commented Feb 18, 2020

it doesnt work with python 3.5

AttributeError: 'list_iterator' object has no attribute 'next'

Instead you can use

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.