Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Loop in a loop?

5 views
Skip to first unread message

Sacred Heart

unread,
Jan 17, 2008, 12:21:55 PM1/17/08
to
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

cokof...@gmail.com

unread,
Jan 17, 2008, 12:35:18 PM1/17/08
to

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.

Sacred Heart

unread,
Jan 17, 2008, 1:38:38 PM1/17/08
to
On Jan 17, 1:35 pm, cokofree...@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?

R,
SH

Chris

unread,
Jan 17, 2008, 1:52:24 PM1/17/08
to

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

cokof...@gmail.com

unread,
Jan 17, 2008, 2:42:42 PM1/17/08
to

couldn't you just do something like

if len(array1) is not len(array2):
if len(array1) < len(array2):
max_length = len(array2) - len(array1)
array1.extend([None for i in xrange(0, max_length)])
elif len(array1) > len(array2):
max_length = len(array1) - len(array2)
array2.extend([None for i in xrange(0, max_length)])

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

Though my case only really works for these two, whereas yours can be
used on more than two lists. :)

Bruno Desthuilliers

unread,
Jan 17, 2008, 2:44:29 PM1/17/08
to
Sacred Heart a écrit :

<ot>
Please gentlemen: Python has no builtin type named 'array', so
s/array/list/g
</ot>


Just pad your shortest list.


cokof...@gmail.com

unread,
Jan 17, 2008, 2:57:46 PM1/17/08
to
>
> > 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?
>
> <ot>
> Please gentlemen: Python has no builtin type named 'array', so
> s/array/list/g
> </ot>
>
> Just pad your shortest list.

I agree, but was merely showing how he would use the variables he had
given.

Duncan Booth

unread,
Jan 17, 2008, 3:20:05 PM1/17/08
to
Chris <cwi...@gmail.com> wrote:

> 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
>

Another option is to pad each iterator as it is exhausted. That way you
can use any iterators not just lists. e.g.

from itertools import cycle, chain

def paddedzip(*args, **kw):
padding = kw.get('padding', '')
def generate_padding():
padders = []
def padder():
if len(padders) < len(args)-1:
padders.append(None)
while 1:
yield padding
while 1:
yield padder()

return zip(*(chain(it, pad)
for (it, pad) in zip(args, generate_padding())))

for i in paddedzip(xrange(10), ['one', 'two', 'three', 'four'],
['a', 'b', 'c'], padding='*'):
print i

Bruno Desthuilliers

unread,
Jan 17, 2008, 4:38:58 PM1/17/08
to
cokof...@gmail.com a écrit :
(snip)

> couldn't you just do something like
>
> if len(array1) is not len(array2):

*never* use the identity operator to test equality ! The fact that
CPython memoize small integers is an implementation detail, *not* a part
of the language specification.

> if len(array1) < len(array2):
> max_length = len(array2) - len(array1)
> array1.extend([None for i in xrange(0, max_length)])
> elif len(array1) > len(array2):
> max_length = len(array1) - len(array2)
> array2.extend([None for i in xrange(0, max_length)])


Never heard of the builtin max() function ?-)

def pad(*lists, **kw):
padding = kw.get('padding', None)
lists_lens = [len(alist) for alist in lists]
padlen = max(lists_lens)
return [
alist + ([padding] * (padlen - list_len))
for list_len, alist in zip(lists_lens, lists)
]

for i in zip(*pad(range(3), range(5, 10))):
print i


Now there are very certainly smart solutions using itertools, but the
one I cooked is way too ugly so I'll leave this to itertools masters !-)

sturlamolden

unread,
Jan 17, 2008, 5:12:47 PM1/17/08
to
On 17 Jan, 13:21, Sacred Heart <scrd...@gmail.com> wrote:

> A push in the right direction, anyone?

for number,letter in zip(array1,array2):
print "%s %s" % (number,letter)


sturlamolden

unread,
Jan 17, 2008, 5:21:16 PM1/17/08
to
On 17 Jan, 14:38, Sacred Heart <scrd...@gmail.com> wrote:

> 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?

In that case your problem is the data. You'll either have to truncate
one array and/or pad the other.

Or is this what you want?

n = len(array1) if len(array1) < len(array2) else len(array2)
for number,letter in zip(array1[:n],array2[:n]):


print "%s %s" % (number,letter)

reminder = array1[n:] if len(array1) > len(array2) else array2[n:]
for x in reminder: print x

Paul Hankin

unread,
Jan 17, 2008, 5:25:45 PM1/17/08
to
On Jan 17, 4:38 pm, Bruno Desthuilliers <bruno.

42.desthuilli...@wtf.websiteburo.oops.com> wrote:
> Now there are very certainly smart solutions using itertools, but the
> one I cooked is way too ugly so I'll leave this to itertools masters !-)

Here's my effort:

from itertools import izip, islice, chain, repeat

def padzip(*xs, **kw):
pad = kw.get('padding', None)
maxlen = max(len(x) for x in xs)
return islice(izip(*[chain(x, repeat(pad)) for x in xs]), maxlen)

--
Paul Hankin

Roel Schroeven

unread,
Jan 17, 2008, 6:14:38 PM1/17/08
to
Sacred Heart schreef:

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

Paul Rubin

unread,
Jan 17, 2008, 6:39:25 PM1/17/08
to
Sacred Heart <scr...@gmail.com> writes:
> 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

The "functional" style is to use the zip function that someone
described. The old-fashioned way is simply:

n = len(array1)
for i in xrange(n):
print array1[i], array2[i]

You can modify this in various ways if the lengths of the lists are
not equal. E.g.

George Sakkis

unread,
Jan 17, 2008, 7:02:34 PM1/17/08
to

And if the iterables don't necessarily support len(), here's a more
general solution:

from itertools import repeat

def izippad(*iterables, **kw):


pad = kw.get('padding', None)

next_pad = repeat(pad).next
getnext = [iter(iterable).next for iterable in iterables]
pending = size = len(iterables)
while True:
slice = [None] * size
for i in xrange(size):
try: slice[i] = getnext[i]()
except StopIteration:
pending -= 1
if not pending: return
getnext[i] = next_pad
slice[i] = pad
yield slice


George

Paul Hankin

unread,
Jan 17, 2008, 11:59:44 PM1/17/08
to

Instead of counting the exceptions, we can limit the padding iterables
by using an iterator that returns len(iterables) - 1 padding
generators, use a sort of lazy chain, and then just izip.

from itertools import izip, repeat

def chain_next(xs, yg):
for x in xs: yield x
for y in yg.next(): yield y

def izippad(*xs, **kw):
padder = repeat(kw.get('padding', None))
padder_gen = repeat(padder, len(xs) - 1)
return izip(*[chain_next(x, padder_gen) for x in xs])

--
Paul Hankin

Paul Rubin

unread,
Jan 18, 2008, 12:13:52 AM1/18/08
to
George Sakkis <george...@gmail.com> writes:
> And if the iterables don't necessarily support len(), here's a more
> general solution:

Not trying to pick on you personally but there's this disease
when a newbie comes with a basically simple question (in this case,
how to solve the problem with ordinary lists) and gets back a lot
of complex, overly general "graduate level" solutions.

There's a humorous set of Haskell examples that takes this to extremes:

http://www.willamette.edu/~fruehr/haskell/evolution.html

Ben Finney

unread,
Jan 18, 2008, 12:31:53 AM1/18/08
to
Paul Rubin <http://phr...@NOSPAM.invalid> writes:

> Not trying to pick on you personally but there's this disease when a
> newbie comes with a basically simple question (in this case, how to
> solve the problem with ordinary lists) and gets back a lot of
> complex, overly general "graduate level" solutions.

Is that a disease?

I would characterise it as symptomatic of a very healthy programming
community. We like interesting problems, and enjoy coming up with ever
more elegant solutions. The discussions that ensue are healthy, not
diseased.

Whether that's exactly what the original poster in such a thread wants
is beside the point. This forum is for the benefit of all
participants, and discussing an apparently simple problem to discover
its complexities is part of the enjoyment.

Enjoyment of the discussion, after all, is the main reward most people
can ever hope to get for participation in most threads here.

--
\ "Remember: every member of your 'target audience' also owns a |
`\ broadcasting station. These 'targets' can shoot back." -- |
_o__) Michael Rathbun to advertisers, news.admin.net-abuse.email |
Ben Finney

George Sakkis

unread,
Jan 18, 2008, 12:41:03 AM1/18/08
to
On Jan 17, 7:13 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:

> George Sakkis <george.sak...@gmail.com> writes:
> > And if the iterables don't necessarily support len(), here's a more
> > general solution:
>
> Not trying to pick on you personally but there's this disease
> when a newbie comes with a basically simple question (in this case,
> how to solve the problem with ordinary lists) and gets back a lot
> of complex, overly general "graduate level" solutions.

Fair enough, although I don't think it's bad to show more general/
efficient/flexible solutions after the simple quick & dirty ones have
been shown, as in this thread. My solution is just a step further from
Paul Hankin's, not a direct response to the OP.

> There's a humorous set of Haskell examples that takes this to extremes:
>
> http://www.willamette.edu/~fruehr/haskell/evolution.html

Hehe.. I remember seeing a similar one for Java and "Hello world"
using more and more elaborate abstractions and design patterns but I
can't find the link.

George

Paul Rubin

unread,
Jan 18, 2008, 12:57:36 AM1/18/08
to
Ben Finney <bignose+h...@benfinney.id.au> writes:
> Enjoyment of the discussion, after all, is the main reward most people
> can ever hope to get for participation in most threads here.

Well then, in that case, what the heck.

from itertools import *


def padzip(*xs, **kw):
pad = kw.get('padding', None)

ts = izip(*[chain(((y,) for y in x), repeat(None)) for x in xs])
def m(t): return tuple((x[0] if x else pad) for x in t)
return imap(m, takewhile(any, ts))

Arnaud Delobelle

unread,
Jan 18, 2008, 3:15:55 AM1/18/08
to
On Jan 17, 11:59 pm, Paul Hankin <paul.han...@gmail.com> wrote:

> Instead of counting the exceptions, we can limit the padding iterables
> by using an iterator that returns len(iterables) - 1 padding
> generators, use a sort of lazy chain, and then just izip.
>
> from itertools import izip, repeat
>
> def chain_next(xs, yg):
>     for x in xs: yield x
>     for y in yg.next(): yield y
>
> def izippad(*xs, **kw):
>     padder = repeat(kw.get('padding', None))
>     padder_gen = repeat(padder, len(xs) - 1)
>     return izip(*[chain_next(x, padder_gen) for x in xs])

I have had the need for such a 'padded zip' before and my
implementation was eerily similar:

from itertools import repeat, chain, izip

def repeatnext(iterator):
val = iterator.next()
while True: yield val

def longzip(default, *iterables):
defaultgen = repeat(default, len(iterables) - 1)
return izip(*[chain(it, repeatnext(defaultgen)) for it in
iterables])

--
Arnaud

Bruno Desthuilliers

unread,
Jan 18, 2008, 9:16:26 AM1/18/08
to
Roel Schroeven a écrit :

> Sacred Heart schreef:
>> On Jan 17, 1:35 pm, cokofree...@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:

Yek ! Should have read the doc more carefully. Height years of Python,
and I didn't knew this one :(

Bruno Desthuilliers

unread,
Jan 18, 2008, 9:18:01 AM1/18/08
to
Paul Rubin a écrit :

> George Sakkis <george...@gmail.com> writes:
>> And if the iterables don't necessarily support len(), here's a more
>> general solution:
>
> Not trying to pick on you personally but there's this disease
> when a newbie comes with a basically simple question (in this case,
> how to solve the problem with ordinary lists) and gets back a lot
> of complex, overly general "graduate level" solutions.

As far as I'm concerned, it's certainly a GoodThing(tm) - everyone
learns in the process.

cokof...@gmail.com

unread,
Jan 18, 2008, 10:03:10 AM1/18/08
to
> Hehe.. I remember seeing a similar one for Java and "Hello world"
> using more and more elaborate abstractions and design patterns but I
> can't find the link.
>
> George

This is not linked to Java but deals with Hello World

http://www.ariel.com.au/jokes/The_Evolution_of_a_Programmer.html

Sacred Heart

unread,
Jan 18, 2008, 10:25:06 AM1/18/08
to
On Jan 17, 7:39 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:

Thank you Paul, and everybody else contributing with answers of
various complexity. Although a whole bunch of them was way too complex
for my simple problem, but that's ok.

I now know how to use map and zip, and also learned some tips and
tricks.

Thanks.

All the best,
SH

0 new messages