473,791 Members | 3,028 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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','th ree','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 1731
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','th ree','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...@gma il.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...@gma il.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','th ree','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_iterab le) max_length: max_length =
len(each_iterab le)
for each_iterable in iterables:
each_iterable.e xtend([None for i in xrange(0,max_le ngth-
len(each_iterab le))])

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_longe st_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.c omwrote:
On Jan 17, 2:35 pm, cokofree...@gma il.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','th ree','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_iterab le) max_length: max_length =
len(each_iterab le)
for each_iterable in iterables:
each_iterable.e xtend([None for i in xrange(0,max_le ngth-
len(each_iterab le))])

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_longe st_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...@gma il.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.c omwrote:
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_iterab le) max_length: max_length =
len(each_iterab le)
for each_iterable in iterables:
each_iterable.e xtend([None for i in xrange(0,max_le ngth-
len(each_iterab le))])

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_paddin g():
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_paddin g())))

for i in paddedzip(xrang e(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,arra y2):
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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2943
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 G23_NA17192.fsa rs7374540 A/C I23_Control.fsa rs7374540 C/C
3
5264
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 have a programmable exit condition. It keeps looping till the channels in its socket map (a dictionary) are closed and don't have any pending reads/writes. If you are using Python threads in your application, by using either the threading or...
43
5604
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 fallacy built on the assumption of mythical infinite all powerfull machines. In reality we deal with finite machines that are capable of two states in a loop, they either terminate, or repeat themselves. In the mythical halting problem scenario...
5
7302
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; int digit3 = 0; for( ; digit1 < 5 ; digit1++ ) {
32
4660
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 where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it offers."
2
2687
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 across some wierd loop behavior. With the pasted code I receive the output that follows. I realize that the code is broken, because the inner loop fails to reset j for each iteration of the outer loop (the fix is commented out). I also know that...
3
3529
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, while the C# for loop ending condition is evaluated on every iteration." Is this accurate? I don't understand how you could get away without evaluating the ending condition at every iteration. Otherwise, how would you
32
2608
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 memories are of but I think I just said loop somewhere inside the loop and it immediately jumped back to the start of the loop and began again. I can't seem to do that in .net. I this functionality available?
16
3541
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 instructions which can sure be optimized away is the check for the break condition, at least within the time where it is known that the loop will not reach it. Any idea how to write such a loop? e.g.
2
19314
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 iterates a specified number of times, requires you to also implement or decrement some sort of Loop Counter, while a For...Next Loop does that work for you. Both Loops will provide the same results, but the For...Next Loop is substantially faster. One...
0
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10155
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9995
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9029
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4110
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.