Skip to content

Instantly share code, notes, and snippets.

@jaquinocode
Created September 1, 2020 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaquinocode/1a4877a4e39a55ad7c6e2e151930dbc3 to your computer and use it in GitHub Desktop.
Save jaquinocode/1a4877a4e39a55ad7c6e2e151930dbc3 to your computer and use it in GitHub Desktop.
A normal generator/iterator that additionally keeps track of the previous element in Python. Also includes an iterator to keep track of next (after) element as well.
from itertools import tee, chain
# ABC -> (None, A) (A, B) (B, C)
def prev_curr_iter(iterable):
a, b = tee(iterable)
return zip(chain([None], a), b)
# use case
for prev, curr in prev_curr_iter("ABC"):
print(f"{prev=}\t{curr=}")
# -------------
# ABC -> (None, A, B) (A, B, C) (B, C, None)
def prev_curr_after_iter(iterable):
a, b, c = tee(iterable, 3)
next(c, None)
return zip(chain([None], a), b, chain(c, [None]))
# use case
for prev, curr, after in prev_curr_after_iter("ABCDEFG"):
print(f"{prev=}\t{curr=}\t{after=}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment