0

I have a list [1,2,3,4,5,6] and I want to iterate over it like

[1,2]
[3,4]
[5,6]

I am able to find a lot of answers using zip() that result in

[1,2]
[2,3]
[3,4]
[4,5]
[5,6]

and I could create a new list from this and iterate over every 2nd element in that list with [::2] but I am wondering if there is a more elegant solution.

Thanks for your help.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
D3l_Gato
  • 1,297
  • 2
  • 17
  • 25

2 Answers2

0

Using zip with a stride of [::2] is the most concise way I can think to achieve this.

>>> data = [1,2,3,4,5,6]
>>> pairs = [[i,j] for i,j in zip(data[::2], data[1::2])]
>>> pairs
[[1, 2], [3, 4], [5, 6]]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

You don't need zip, you can achieve what you want with a simple generator like this:

def pairs(iterable):
    for i in range(0, len(iterable), 2):
        yield iterable[i:i+2]

Another solution that does not require iterable to be indexable or have a known length, and therefore is more general, is to use iter():

def pairs(iterable):
    it = iter(iterable)

    while True:
        yield next(it), next(it)

This will automatically stop when next() raises StopIteration to indicate that the iterable doesn't have any more items.

In both of the cases you can then do:

for a, b in pairs([1,2,3,4,5,6]):
    print(a, b)
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128