list

Iterating Python Lists 2 by 2

Not necessarily the most superior way performance/Pythonicity wise but it’s simple to remember and short:

list = [1, 2, 3, 4, 5, 6, ...]
pairs = zip(list[::2], list[1::2])
for pair in pairs:
    # do stuff

pair will be (1, 2), (3, 4) etc.
The 2 list slices turn the original into odd/even sets and zip merges them

 Scroll to top