Loop in a loop?

Chris cwitts at gmail.com
Thu Jan 17 08:52:24 EST 2008


On Jan 17, 2:35 pm, cokofree... at gmail.com wrote:
> On Jan 17, 1:21 pm, Sacred Heart <scrd... at gmail.com> wrote:
>
>
>
> > Hi,
> > I'm new to Python and have come across a problem I don't know how to
> > solve, enter com.lang.python :)
>
> > I'm writing some small apps to learn the language, and I like it a lot
> > so far.
>
> > My problem I've stumbled upon is that I don't know how to do what I
> > want. I want to do a loop in a loop. I think.
>
> > I've got two arrays with some random stuff in, like this.
>
> > array1 = ['one','two','three','four']
> > array2 = ['a','b','c','d']
>
> > I want to loop through array1 and add elements from array2 at the end,
> > so it looks like this:
>
> > one a
> > two b
> > three c
> > four c
>
> > I'm stuck. I know how to loop through the arrays separatly and print
> > them, but both at the same time? Hmmm.
>
> > A push in the right direction, anyone?
>
> > R,
> > SH
>
> 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.

You could always pre-pad the lists you are using before using the zip
function, kinda like

def pad(*iterables):
    max_length = 0
    for each_iterable in iterables:
        if len(each_iterable) > max_length: max_length =
len(each_iterable)
    for each_iterable in iterables:
        each_iterable.extend([None for i in xrange(0,max_length-
len(each_iterable))])

pad(array1, array2, array3)
for i in zip(array1, array2, array3):
    print i

What you could also do is create an index to use for it.

for i in xrange(0, length_of_longest_list):
    try: print array1[i]
    except IndexError: pass
    try: print array2[i]
    except IndexError: pass



More information about the Python-list mailing list