D
D
Dmitry2018-07-16 17:03:44
Python
Dmitry, 2018-07-16 17:03:44

How to iterate over pairs in a Python list?

Let there be an Iterable instance. How can I get the first pair of elements in the first step, the second in the second, and so on?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Bragin, 2018-07-16
@cosmoskey

https://docs.python.org/3/library/itertools.html#i...
search there pairwise for variant (s0, s1), (s1, s2), ...
for variant (s0, s1), (s2, s3), ...

from itertools import zip_longest

def pairwise(iterable, count):
    return zip_longest(*[iter(iterable)] * count, fillvalue=None)

R
Ruslan., 2018-07-16
@LaRN

You can try like this:

var = (0,1,2,3,4,5)
var = iter(var)

try:
  while True:
      a = next(var)
      b = next(var)
      print(str(a) + " - " + str(b))
except StopIteration:
  print('stop')

at the output of the pair:
0 - 1
2 - 3
4 - 5
stop

P
Pavel Aksenov, 2018-07-17
@hellmin

l = list(range(0, 10))
zip(l[0::2], l[1::2])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question