The Python Oracle

How do I loop through a list by twos?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over

--

Chapters
00:00 Question
00:27 Accepted answer (Score 483)
00:55 Answer 2 (Score 137)
01:23 Answer 3 (Score 77)
01:45 Answer 4 (Score 43)
02:23 Thank you

--

Full question
https://stackoverflow.com/questions/2990...

Answer 3 links:
[recipe]: http://docs.python.org/library/itertools...
[itertools]: http://docs.python.org/library/itertools...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #loops #forloop #iteration

#avk47



ACCEPTED ANSWER

Score 494


You can use a 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.




ANSWER 2

Score 142


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.




ANSWER 3

Score 46


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.




ANSWER 4

Score 7


nums = range(10)
for i in range(0, len(nums)-1, 2):
    print nums[i]

Kinda dirty but it works.