[Tutor] Iterating over two sequences in "parallel"

Jose Amoreira ljmamoreira at gmail.com
Sat Nov 28 12:03:30 CET 2009


Yes, Robert, that does it! Thanks a lot!
Have a nice weekend!
Jose

On Saturday 28 November 2009 10:54:56 am Robert Johansson 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...
> 
> Maybe enumerate is what you are looking for?
> 
> list1=range(10)
> list2=range(10,20)
> for index, element in enumerate(list1):
>     print element, list2[index]
> 
> /Robert
> 


More information about the Tutor mailing list