Iterating through multiple sequences

Jørgen Cederberg jorgencederberg at
Thu Oct 31 11:50:42 CET 2002

"Mark Charsley" <mark.charsley at> wrote in message news:memo.20021031104532.116B at
> In several cases recently I've wanted to iterate through two sequences at 
> the same time. The way I've been doing it so far is
>     assert(len(myList1) == len(myList2))
>     for i in range(len(myList1)):
>         doSomethingWith(myList1[i],myList2[i])
> which is a little ugly. Is there some clever idiom I'm missing that would 
> simplify things? Something like
>     for elem1,elem2 in myList1,myList2:
>         doSomethingWith(elem1,elem2)

Instead you can use the function zip:

for elem1, elem2 in zip(mylist1, mylist2):
    doSomethingWith(elem1, elem2)

zip merges the list into tuples.


More information about the Python-list mailing list