How do I loop through a list by twos? [duplicate]
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.