Iterating Python Lists 2 by 2

xster
xster
Published in
1 min readDec 8, 2012

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

--

--