A little more advanced for loop

Larry Bates larry.bates at websafe.com
Fri Feb 9 17:35:32 EST 2007


Horta wrote:
> On Feb 9, 9:00 am, Stephan Diehl <stephan.di... at gmx.net> wrote:
>> Horta wrote:
>>>     Hi folks,
>>>   Suppose I have to loop over 3 lists being the same size at the same
>>> time and order. How can I do that without using the range() function
>>> or whatever indexing?
>>> Example using range:
>>> a = ['aaa', 'aaaa']
>>> b = ['bb', 'bbbb']
>>> c = ['c', 'cccc']
>>> for i in range(len(a)):
>>>     # using a[i], b[i], and c[i]
>>>   I'm sure there's a elegant way to do that...
>>>   Thanks in advance.
>> Sure, there is:
>>
>> for a_item, b_item , c_item in zip(a,b,c):
>>         # do something
> 
>   Thanks guys!
> 
Note: if lists are long take a look at itertools izip.  zip creates
a list of lists which could take lots of memory/time if they are VERY
large.  itertools izip iterates over them in place.

from itertools import izip

for a_item, b_item, c_item in izip(a,b,c):
    # do something

-Larry



More information about the Python-list mailing list