Iterating through multiple sequences
David Brown
david at no.westcontrol.spam.com
Thu Oct 31 06:27:37 EST 2002
"Mark Charsley" <mark.charsley at REMOVE_THIS.radioscape.com> wrote in message
news:memo.20021031104532.116B at a.radioscape.com...
> 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)
>
> which, while valid python, doesn't do what I hoped for
>
Try either zip(..., ..) or map(None, ..., ...). The difference is how they
treat unequal lengths:
>>> as = [1, 2, 3]
>>> bs = ['a', 'b']
>>> zip(as, bs)
[(1, 'a'), (2, 'b')]
>>> map(None, as, bs)
[(1, 'a'), (2, 'b'), (3, None)]
>>>
More information about the Python-list
mailing list