# How do I loop through a list by twos?

### Question

Possible Duplicate:
What is the most “pythonic” way to iterate over a list in chunks?

I want to loop through a Python list and process 2 list items at a time. Something like this in another language:

``````for(int i = 0; i < list.length(); i+=2)
{
// do something with list[i] and list[i + 1]
}
``````

What's the best way to accomplish this?

1
221
11/11/2017 9:41:51 PM

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.

331
5/11/2016 10:48:32 AM

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 9

for 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.