You can zip
the list with itself sans the first element:
a = [5, 7, 11, 4, 5]
for previous, current in zip(a, a[1:]):
print(previous, current)
This works even if your list has no elements or only 1 element (in which case zip
returns an empty iterable and the code in the for
loop never executes). It doesn't work on generators, only sequences (tuple
, list
, str
, etc).