Skip to content

Instantly share code, notes, and snippets.

@TENorbert
Created December 21, 2018 17:31
Show Gist options
  • Save TENorbert/6bc68eb86dc3ddc96e723d80b6f8080f to your computer and use it in GitHub Desktop.
Save TENorbert/6bc68eb86dc3ddc96e723d80b6f8080f to your computer and use it in GitHub Desktop.
Get previous, Current and Next Items from any iterable object in Python 3
from itertools import tee, islice, chain
def get_previous_current_and_next(iterable_object):
prev_item, cur_item, next_item = tee(iterable_object, 3)
prev_item = chain([None], prev_item)
next_item = chain(islice(next_item, 1, None), [None])
return zip(prev_item, cur_item, next_item)
# Test Code:
gate_list = ['Gate1', 'Gate2', 'Gate3', 'Gate4', 'Gate5', 'Gate6']
for prev_gate, cur_gate, next_gate in get_previous_and_next(gate_list):
print("Current Gate is : {0} , Previous Gate was : {1} , Next Gate will be: {2} \n".format(cur_gate, prev_gate, next_gate))
# Output:
'''
Current Gate is : Gate1 , Previous Gate was : None , Next Gate will be: Gate2
Current Gate is : Gate2 , Previous Gate was : Gate1 , Next Gate will be: Gate3
Current Gate is : Gate3 , Previous Gate was : Gate2 , Next Gate will be: Gate4
Current Gate is : Gate4 , Previous Gate was : Gate3 , Next Gate will be: Gate5
Current Gate is : Gate5 , Previous Gate was : Gate4 , Next Gate will be: Gate6
Current Gate is : Gate6 , Previous Gate was : Gate5 , Next Gate will be: None
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment