Use zip():
for elem1, elem2 in zip(list1, list2):
If one of these lists is longer than the other, you won't see the elements beyond the length of the shorter list.
On python 2, zip()
results in a copy of both lists zipped together, and for large lists that can be a memory burden. Use itertools.izip() for such larger lists, it returns an iterator instead. On python 3, zip()
itself already returns an iterator.
If you need to loop over the longest list instead (and fill in a filler value for the missing shorter list elements), use itertools.izip_longest() instead:
from itertools import izip_longest
for elem1, elem2 in izip_longest(list1, list2):