How do I loop through a list by twos?

froadie picture froadie · Jun 7, 2010 · Viewed 480.3k times · Source

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?

Answer

Brian R. Bondy picture Brian R. Bondy · Jun 7, 2010

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.