How to get the previous element when using a for loop? [duplicate]

You can use zip:

for previous, current in zip(li, li[1:]):
    print(previous, current)

or, if you need to do something a little fancier, because creating a list or taking a slice of li would be inefficient, use the pairwise recipe from itertools

import itertools

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

for a, b in pairwise(li):
    print(a, b)

Leave a Comment