Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Python

Idiom #163 Print list elements by group of 2

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

for x in zip(list[::2], list[1::2]):
    print(x)

original list is called list
for x in range(0, len(list), 2):
    print(list[x], list[x + 1])
from itertools import zip_longest
x = iter(list)
print(*zip_longest(x, x))
from itertools import batched
for x in batched(a, 2): print(x)

Python 3.12+
from itertools import tee
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)

Official documentation suggestion. Works for any iterable
#include <stdio.h>
for (unsigned i = 0; i < sizeof(list) / sizeof(list[0]); i += 2)
	printf("%d, %d\n", list[i], list[i + 1]);

I'm treating list as an array not a list because C doesn't have lists built in.
The length had better be even or there'll be undefined behaviour to pay!

New implementation...