# variable counter for python How do I loop through a list by twos?

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.

python for loop list

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?

If you're using Python 2.6 or newer you can use the grouper recipe from the `itertools` module:

``````from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
``````

Call like this:

``````for item1, item2 in grouper(2, l):
# Do something with item1 and item2
``````

Note that in Python 3.x you should use `zip_longest` instead of `izip_longest`.

This might not be as fast as the izip_longest solution (I didn't actually test it), but it will work with python < 2.6 (izip_longest was added in 2.6):

``````from itertools import imap

def grouper(n, iterable):
"grouper(3, 'ABCDEFG') --> ('A,'B','C'), ('D','E','F'), ('G',None,None)"
args = [iter(iterable)] * n

return imap(None, *args)
``````

If you need to go earlier than 2.3, you can substitute the built-in map for imap. The disadvantage is that it provides no ability to customize the fill value.

### Tags

python   list   loops   for-loop   iteration