Loop in a loop?

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Thu Jan 17 13:14:38 EST 2008


Sacred Heart schreef:
> On Jan 17, 1:35 pm, cokofree... at gmail.com wrote:
>> for i in zip(array1, array2):
>>     print i
>>
>> Although I take it you meant four d, the issue with this method is
>> that once you hit the end of one array the rest of the other one is
>> ignored.
> 
> Yes, small typo there.
> 
> Okey, so if my array1 is has 4 elements, and array2 has 6, it won't
> loop trough the last 2 in array2? How do I make it do that?

One solution is with map() instead if zip(). map() with None as the 
first argument works much like zip(), but it keeps looping if one of the 
lists is exhausted. When that happens, it uses None for those values:

words = ['zero', 'one', 'two', 'three']
numbers = [0, 1, 2, 3, 4, 5, 6]
for word, number in map(None, words, numbers):
     print word, number


zero 0
one 1
two 2
three 3
None 4
None 5
None 6

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
   -- Isaac Asimov

Roel Schroeven



More information about the Python-list mailing list