473,396 Members | 1,996 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Loop in a loop?

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
23 1687
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
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
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
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
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
>
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Charles Alexander | last post by:
Hello I am new to php & MySQL - I am trying to retrieve some records from a MySQL table and redisplay them. The data in list form looks like this: Sample_ID Marker_ID Variation ...
3
by: Anand Pillai | last post by:
This is for folks who are familiar with asynchronous event handling in Python using the asyncore module. If you have ever used the asyncore module, you will realize that it's event loop does not...
43
by: Gremlin | last post by:
If you are not familiar with the halting problem, I will not go into it in detail but it states that it is impossible to write a program that can tell if a loop is infinite or not. This is a...
5
by: Martin Schou | last post by:
Please ignore the extreme simplicity of the task :-) I'm new to C, which explains why I'm doing an exercise like this. In the following tripple nested loop: int digit1 = 1; int digit2 = 0;...
32
by: Toby Newman | last post by:
At the page: http://www.strath.ac.uk/IT/Docs/Ccourse/subsection3_8_3.html#SECTION0008300000000000000 or http://tinyurl.com/4ptzs the author warns: "The for loop is frequently used, usually...
2
by: Alex | last post by:
Compiler - Borland C++ 5.6.4 for Win32 Copyright (c) 1993, 2002 Borland Linker - Turbo Incremental Link 5.65 Copyright (c) 1997-2002 Borland Platform - Win32 (XP) Quite by accident I stumbled...
3
by: Ben R. | last post by:
In an article I was reading (http://www.ftponline.com/vsm/2005_06/magazine/columns/desktopdeveloper/), I read the following: "The ending condition of a VB.NET for loop is evaluated only once,...
32
by: cj | last post by:
When I'm inside a do while loop sometimes it's necessary to jump out of the loop using exit do. I'm also used to being able to jump back and begin the loop again. Not sure which language my...
16
by: Claudio Grondi | last post by:
Sometimes it is known in advance, that the time spent in a loop will be in order of minutes or even hours, so it makes sense to optimize each element in the loop to make it run faster. One of...
2
ADezii
by: ADezii | last post by:
If you are executing a code segment for a fixed number of iterations, always use a For...Next Loop instead of a Do...Loop, since it is significantly faster. Each pass through a Do...Loop that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.