Iterating Python Lists 2 by 2

xster
xster in xster
Dec 8, 2012 · 1 min read

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

xster

Collection of tech tips and learnings

xster

Written by

xster

xster

xster

Collection of tech tips and learnings