Logo

Programming-Idioms

History of Idiom 163 > diff from v15 to v16

Edit summary for version 16 by sgdpk:
New Python implementation by user [sgdpk]

Version 15

2019-09-26, 19:01:59

Version 16

2019-09-27, 04:00:54

Idiom #163 Print list elements by group of 2

Print all the list elements, two by two, assuming list length is even.

Idiom #163 Print list elements by group of 2

Print all the list elements, two by two, assuming list length is even.

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

for a, b in pairwise(list):
    print(a, b)
Comments bubble
Official documentation suggestion. Works for any iterable
Doc URL
https://docs.python.org/3.6/library/itertools.html#itertools-recipes
Origin
https://docs.python.org/3.6/library/itertools.html#itertools-recipes