How do I loop through a list by twos? [duplicate] How do I loop through a list by twos? [duplicate] python python

How do I loop through a list by twos? [duplicate]


You can use for in range with a step size of 2:

Python 2

for i in xrange(0,10,2):  print(i)

Python 3

for i in range(0,10,2):  print(i)

Note: Use xrange in Python 2 instead of range because it is more efficient as it generates an iterable object, and not the whole list.


You can also use this syntax (L[start:stop:step]):

mylist = [1,2,3,4,5,6,7,8,9,10]for i in mylist[::2]:    print i,# prints 1 3 5 7 9for i in mylist[1::2]:    print i,# prints 2 4 6 8 10

Where the first digit is the starting index (defaults to beginning of list or 0), 2nd is ending slice index (defaults to end of list), and the third digit is the offset or step.


The simplest in my opinion is just this:

it = iter([1,2,3,4,5,6])for x, y in zip(it, it):    print x, yOut: 1 2     3 4     5 6

No extra imports or anything. And very elegant, in my opinion.


matomo