By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,695 Members | 1,338 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,695 IT Pros & Developers. It's quick & easy.

Loop in a loop?

P: n/a
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
Jan 17 '08 #1
Share this Question
Share on Google+
23 Replies


P: n/a
On Jan 17, 1:21 pm, Sacred Heart <scrd...@gmail.comwrote:
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.
Jan 17 '08 #2

P: n/a
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

Jan 17 '08 #3

P: n/a
On Jan 17, 2:35 pm, cokofree...@gmail.com wrote:
On Jan 17, 1:21 pm, Sacred Heart <scrd...@gmail.comwrote:
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
Jan 17 '08 #4

P: n/a
On Jan 17, 2:52 pm, Chris <cwi...@gmail.comwrote:
On Jan 17, 2:35 pm, cokofree...@gmail.com wrote:
On Jan 17, 1:21 pm, Sacred Heart <scrd...@gmail.comwrote:
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
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. :)
Jan 17 '08 #5

P: n/a
Sacred Heart a écrit :
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?
<ot>
Please gentlemen: Python has no builtin type named 'array', so
s/array/list/g
</ot>
Just pad your shortest list.
Jan 17 '08 #6

P: n/a
>
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.
Jan 17 '08 #7

P: n/a
Chris <cw****@gmail.comwrote:
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

Jan 17 '08 #8

P: n/a
On 17 Jan, 13:21, Sacred Heart <scrd...@gmail.comwrote:
A push in the right direction, anyone?
for number,letter in zip(array1,array2):
print "%s %s" % (number,letter)
Jan 17 '08 #9

P: n/a
On 17 Jan, 14:38, Sacred Heart <scrd...@gmail.comwrote:
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



Jan 17 '08 #10

P: n/a
On Jan 17, 4:38 pm, Bruno Desthuilliers <bruno.
42.desthuilli...@wtf.websiteburo.oops.comwrote:
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
Jan 17 '08 #11

P: n/a
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:

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
Jan 17 '08 #12

P: n/a
Sacred Heart <sc*****@gmail.comwrites:
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.
Jan 17 '08 #13

P: n/a
On Jan 17, 12:25 pm, Paul Hankin <paul.han...@gmail.comwrote:
On Jan 17, 4:38 pm, Bruno Desthuilliers <bruno.

42.desthuilli...@wtf.websiteburo.oops.comwrote:
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
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
Jan 17 '08 #14

P: n/a
On Jan 17, 7:02*pm, George Sakkis <george.sak...@gmail.comwrote:
On Jan 17, 12:25 pm, Paul Hankin <paul.han...@gmail.comwrote:
On Jan 17, 4:38 pm, Bruno Desthuilliers <bruno.
42.desthuilli...@wtf.websiteburo.oops.comwrote:
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

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

Jan 18 '08 #15

P: n/a
George Sakkis <ge***********@gmail.comwrites:
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/ha...evolution.html
Jan 18 '08 #16

P: n/a
Paul Rubin <http://ph****@NOSPAM.invalidwrites:
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
Jan 18 '08 #17

P: n/a
On Jan 17, 7:13 pm, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
George Sakkis <george.sak...@gmail.comwrites:
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/ha...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
Jan 18 '08 #18

P: n/a
Ben Finney <bi****************@benfinney.id.auwrites:
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))
Jan 18 '08 #19

P: n/a
On Jan 17, 11:59*pm, Paul Hankin <paul.han...@gmail.comwrote:
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

Jan 18 '08 #20

P: n/a
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 :(

Jan 18 '08 #21

P: n/a
Paul Rubin a écrit :
George Sakkis <ge***********@gmail.comwrites:
>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.

Jan 18 '08 #22

P: n/a
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_Ev...rogrammer.html
Jan 18 '08 #23

P: n/a
On Jan 17, 7:39 pm, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
Sacred Heart <scrd...@gmail.comwrites:
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.
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
Jan 18 '08 #24

This discussion thread is closed

Replies have been disabled for this discussion.