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

Brian van den Broek bvande at po-box.mcgill.ca
Tue Nov 30 03:26:37 CET 2004

Hi all,

in a recent post in the "comapring lists" thread, Danny Yoo wrote:

> whenever I see nested loops
> like this, I get nervous.  *grin*

This got me thinking about general design issues. In various programs I 
  have made much use of nested loops in order to parse data files. I've 
done this in cases where I am interested in pulling out some data which 
is identified by a delimiter. Below is a minimal example of the sort of 
thing I have been doing:

date_flag = '[Date]'
email_flag = '[Email]'
item_flags = [date_flag, email_flag]

def parse_file(list_of_lines):
     data_dict = {}
     for line in list_of_lines:
         for item in item_flags:
             if line.startswith(item):
                 data_dict[item] = line[len(item):]
     return data_dict

In this particular toy case, the "for i in item_flags" isn't too much 
help, as I've only listed two delimiters. But I often have a good many 
more, and thus thought the nested loop much better than a long list of 
if-tests. Since the logic in the "for item in item_flags:" loop is quite 
small, it never occurred to be to move it into its own function.

I think I see that the nervous-making aspect of nested loops comes from 
concern about clarity of control flow. (Is there some other worry I'm 
missing?) But is my sort of case one which shows a rule of thumb isn't a 
rigid law? Is there a much better design for my task that I've missed? 
Do more experience folk doubt my wisdom in taking the embedded loop to 
be too short to bother factoring out?

Thanks for any input. Best to all,

Brian vdB

More information about the Tutor mailing list