473,574 Members | 2,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Counting nested loop iterations

What is the best way to count nested loop iterations? I can only figure
to use an index but that seems kludgy.

index = 0
for animal in zoo:
for color in animal:
index += 1

Thanks,
Derek Basch

Mar 16 '06 #1
18 3697
Derek Basch wrote:
What is the best way to count nested loop iterations? I can only figure
to use an index but that seems kludgy.

index = 0
for animal in zoo:
for color in animal:
index += 1


what's kludgy with using a counter to count things ?

(the real question here is of course why you need the counter. what's
the loop doing? if the code you posted is all you have, you can replace
it with index = sum(len(animal) for animal in zoo), but I assume you want
to do more stuff in there...)

</F>

Mar 16 '06 #2
Derek Basch wrote:
What is the best way to count nested loop iterations? I can only figure
to use an index but that seems kludgy.

index = 0
for animal in zoo:
for color in animal:
index += 1


Depending on the types of the containers in question, you could use:

len(zoo) * len(animal)

Mar 16 '06 #3

Fredrik Lundh wrote:
what's kludgy with using a counter to count things ?
Ohhh, nothing in particular. Just seeing if there is a better way to do
it.
(the real question here is of course why you need the counter. what's
the loop doing? if the code you posted is all you have, you can replace
it with index = sum(len(animal) for animal in zoo), but I assume you want
to do more stuff in there...)

</F>


Yes, I am doing more. Your example assumes that all that animals have
the same amount of colors. Not a bad assumption considering I didn't
say anything about that. Looks like good old counters are they way to
go then.

Mar 16 '06 #4
> Depending on the types of the containers in question, you could use:

len(zoo) * len(animal)


I think this would give me the total iterations but I wouldn't be able
to get a running count. Correct?

Thanks for the reply,
Derek Basch

Mar 16 '06 #5
Hi Derek

I went for an embarrassingly long time without knowing about
"enumerate( )". It doesn't directly answer your question about counting
*within* nests, but I am going to tell you this on the off chance you
don't know yet (and apologies if you do):

This:

count = 0
for animal in zoo:
a = animal
anum = count
count = count + 1

IS a kludge, when you have this available to you:

for count, animal in enumerate(zoo):
a = animal
anum = count

I won't say how long it took me to start using list comprehensions :)

regards
Caleb

Mar 16 '06 #6
Derek Basch wrote:
Fredrik Lundh wrote:
(the real question here is of course why you need the counter. what's
the loop doing? if the code you posted is all you have, you can replace
it with index = sum(len(animal) for animal in zoo), but I assume you want
to do more stuff in there...)

</F>

Yes, I am doing more. Your example assumes that all that animals have
the same amount of colors.


No, it doesn't. Fredrik wrote
index = sum(len(animal) for animal in zoo)

The expression (len(animal) for animal in zoo) yields a sequence of the
lengths of the individual animals; passing this to sum() gives the total
count.

Kent
Mar 16 '06 #7
Derek Basch wrote:
index = 0
for animal in zoo:
for color in animal:
index += 1 # assuming there is something more goes here...


You could do this, but it kind of depends what the loop *really* looks
like:

for index, color in enumerate(color
for animal in zoo
for color in animal):
# the something more goes here.
pass
Mar 16 '06 #8
Derek Basch wrote:
What is the best way to count nested loop iterations? I can only figure
to use an index but that seems kludgy.

index = 0
for animal in zoo:
for color in animal:
index += 1


I don't know if it's kludgy, but I do prefer to set counters in the for
statement whenever I can. If I were using 2.4, I might try writing
something like:

for i,(animal,zoo) in enumerate((anim al,zoo) for animal in zoo for
color in animal):
pass

or maybe break it down a little for clarity:

aciter = ((animal,zoo) for animal in zoo for color in animal)
for i,(animal,zoo) in enumerate(acite r):
pass

But even the clear version isn't as nearly clear and straightforward as
the nested fors with the counter. I wouldn't forsake that clarity just
so it isn't "kludgy".
Carl Banks

Mar 16 '06 #9

Carl Banks wrote:
But even the clear version isn't as nearly clear and straightforward as
the nested fors with the counter. I wouldn't forsake that clarity just
so it isn't "kludgy".
Carl Banks


Yeah, looks like using the counters is clearer. Thanks for the opinions
everyone!

Derek Basch

Mar 16 '06 #10

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

Similar topics

25
12686
by: chad | last post by:
I am writing a program to do some reliability calculations that require several nested for-loops. However, I believe that as the models become more complex, the number of required for-loops will increase. Does Python have a limit on the number of nested for-loops? Thanks.
47
12069
by: Mountain Bikn' Guy | last post by:
Take some standard code such as shown below. It simply loops to add up a series of terms and it produces the correct result. // sum numbers with a loop public int DoSumLooping(int iterations) { int result = 0; for(int i = 1;i <=iterations;i++) { result += i;
46
9886
by: Neptune | last post by:
Hello. I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)" (Sam's series), and for nested loops, he writes (p116) "It's often necessary to create a loop even when you are already in a loop." Then he goes on to portray a contrived example that doesn't tell me under what conditions a nested loop might be favoured as a...
7
2572
by: Daniel Vallstrom | last post by:
I am having trouble with floating point addition because of the limited accuracy of floating types. Consider e.g. x0 += f(n) where x0 and f are of some floating type. Sometimes x0 is much larger than f(n) so that x0 + f(n) == x0. For example, x0 could be 2**300*(1.1234...) while f(n) is 2**100*(1.4256...). If x0 + f(n) == x0 I still sometimes...
7
4795
by: sathyashrayan | last post by:
Group, Following function will check weather a bit is set in the given variouble x. int bit_count(long x) { int n = 0; /* ** The loop will execute once for each bit of x set,
2
1613
by: tony collier | last post by:
Hi i want to get a user to input x which then creates an nested loop with x levels. each level of the loop has the same number of iterations e.g. for the case where x=3, the following code is executed int i=new int; for (i=0;i<limit;i++)
5
3535
by: sololoquist | last post by:
#define COUNT_UP #include <stdio.h> #define N 10 int main() { int i; #ifdef COUNT_UP for (i = 0; i < N; i++)
3
1894
by: Dieter Maurer | last post by:
I met the following surprising behaviour .... for i in range(3): .... def gen1(): .... yield i .... yield i, gen1() .... .... 0 0 1 1
13
2684
by: Fredrik Lundh | last post by:
Patrol Sun wrote: so why exactly are you trying to nest 20 or 100 for-in loops? </F>
0
7803
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...
0
7720
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7810
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...
0
8096
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...
1
5618
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...
0
3739
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3749
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2240
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
0
1056
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...

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.