[Tutor] Iterating through a list of strings

Stefan Behnel stefan_ml at behnel.de
Mon May 3 08:49:03 CEST 2010


Thomas C. Hicks, 03.05.2010 07:16:
> %Comment introducing the next block of packages
> %Below are the packages for using Chinese on the system
> %Third line of comment because I am a verbose guy!
> ibus-pinyin
> ibus-table-wubi
> language-pack-zh-hans
>
> etc.
>
> I read the lines of the file into a list for processing.  To strip
> out the comments lines I am using something like this:
>
> for x in lines:
>      if x.startswith('%'):
>          lines.remove(x)
 >
> This works great for all incidents of comments that are only one
> line.  Sometimes I have blocks of comments that are more than one
> line and find that the odd numbered lines are stripped from the list
> but not the even numbered lines

You are modifying the list during iteration, so the size changes and the 
iterator gets diverted. Don't remove the line, just skip over it, e.g.

     def read_package_names(open_text_file):
         """Read lines, strip any comments and return only the
         package names found.
         """
         for line in open_text_file:
             if '%' in line:
                 # take only the part before the '%'
                 line = line.split('%', 1)[0]
             line = line.strip()
             if line:
                 yield line

     with open('packages.txt') as f:
         for package_name in read_package_names(f):
             print package_name

Stefan



More information about the Tutor mailing list