[Tutor] Question about nested FOR looping

stuart_clemons@us.ibm.com stuart_clemons@us.ibm.com
Wed Apr 30 09:27:39 2003




Hi all:

I'm a newbie playing around with nested FOR loops using readlines or a
defined list.  I noticed the looping action of the nested FOR is different
depending on if the input data is coming from a file (readlines) or a
defined list.  Note, that only the nested FOR input source makes a
difference in the output results.  The data source of the top level FOR
loop doesn't seem to affect the looping action of the nested FOR.

Below are the program and results.  Can anyone explain why the looping
action is different depending on the nested FOR input source (readlines vs
defined list) ?

Please let me know if this not clear.  (It doesn't look all that clear to
me !)

Here's the text file, subitems.txt:
1
3
5

Nested looping from a defined list:

###### Start Program #######

import string
mF = file('g:\python22\sctest\\master.txt', 'r')   # This file contains the
same data as the master list (below)
#sF = file('g:\python22\sctest\\subitems.txt', 'r') # This file contains
the same data as the subitems list (below)

#master = ['1', '2', '3', '4', '5']       # This list = Master.txt (above)
subitems = ['1', '3', '5']                # This list = subitems.txt
(above)

for m in mF.readlines():    # Read data from master.txt file
#for m in master:           # Or, read data for master list
      m = m.strip()

      #for s in sF.readlines():    # Read data from subitems.txt file
      for s in subitems:         # Or, read data from subitems list
            s = s.strip()
            if s == m:
            print "this num is duplicate: ", m
            break
      if s <> m:
      print "this num is unique: ", m

###### End Program #########

The result of running the program is this:

this num is duplicate:  1
this num is unique:  2
this num is duplicate:  3
this num is unique:  4
this num is duplicate: 5


If the nested loop uses readlines to input data from subitems.txt, the
result is this:

this num is duplicate:  1
this num is unique:  2
this num is unique:  3
this num is unique:  4
this num is unique:  5

Why are they different ?

TIA