[Tutor] design question -- nested loops considered harmful?

Alan Gauld alan.gauld at freenet.co.uk
Tue Nov 30 10:21:22 CET 2004


> I think I see that the nervous-making aspect of nested loops comes
from
> concern about clarity of control flow.

Thats one aspect. The likeliehood of introducing bugs increases
with the depth of indentation level. THats one of the strongest
arguments for functional programming since it tends to reduce the
number of levels of indentation. Its to do with control of scopes...

> (Is there some other worry I'm  missing?)

The other big problem with nested loops specifically is performance.
They look innocuous and its easy to forget that the number of times
the innermost level gets executed in the product of all the loop
counters:

for j in range(10):
    for k in range(20):
        for m in range (5):
           print "this gets done 1000 times..."

> But is my sort of case one which shows a rule of thumb isn't a
> rigid law?

There are no rigid laws just principles. So long as you understand
the consequences, and their impact then you can do what you want.

> Is there a much better design for my task that I've missed?

A list comprehension or other FP construct such as filter() might
be appropriate.

> Do more experience folk doubt my wisdom in taking the embedded loop
to
> be too short to bother factoring out?

No, a loop over two items is not likely to be a major concern,
but equally a simple if test might be more appropriate. And
recall that you can often use boolean operators to eliminate
multiple tests:

item_flags = [date_flag, email_flag]
     ...
     for line in list_of_lines:
         if line.startswith(date_flag) or line.startswith(email_flag):
                 doSomething()
                 break

But in your case, since you are using the object of the test you
would need to split it up anyway. But an if/elif chain would be
faster than the loop and avoid the break statement (which is
also a "bad thing" in a purist sense because it breaks the rules
of structured programming). But if you then tidied it up by putting
the if/elif in a function you would lose the speed advantage!
(But you would gain a clarity advantage and reduce the indentation
level)

Hopefully the above paragraph hints at the multitude of compromises
you have to mentally deal with in writing "good" code. (Usually
complex code is a sign of complex data and you are best off
looking at reformatting your data to allow a simpler design!)
As a beginner it's better to just focus on getting it to work.
Afterwards you can clean it up as time allows. (As a professional
you should get it peer reviewed and follow whatever coding
standards exist in your office...)

HTH,

Alan G.




More information about the Tutor mailing list