[Tutor] Iterating over two sequences in "parallel"
Dave Angel
davea at ieee.org
Sat Nov 28 13:59:04 CET 2009
Jose Amoreira wrote:
> Hi!
> I want to process corresponding elements of two lists, sequentially. Call the
> lists list1 and list2, and assume they have equal lengths. I can do something
> like
>
> for index in range(len(list1)):
> process(list1[index], list2[index])
>
> But I find it somehow rather ugly, because we generate yet another an list for
> the index, when we already have the two we want to process. I know we can use
> xrange, but still I find it awkward...
>
> Instead of the above snippet, I am considering something like
>
> while list1:
> process(list1.pop(), list2.pop())
>
> But this has the side effect of emptying both lists, which may not be
> convenient. Of course we can make backup copies of the lists if needed, but we
> are then recovering the previous method ugliness...
>
> Do you guys have any suggestions regarding this? Thanks
> Jose Amoreira
>
>
(following is untested, and from memory, so I may not have it perfect.
But it's close)
This is exactly what zip() is for.
zip(list1, list2)
yields a new list that consists of tuples taken in sequence from those
two lists. So
for item1, item2 in zip(list1, list2):
process(item1, item2)
And if the lists are large, use itertools.izip() which works the same,
but produces an iterator.
Note that if the lists are not the same length, I think it stops when
the shorter one ends.
DaveA
More information about the Tutor
mailing list