[Tutor] Iterating through a list of strings

Luke Paireepinart rabidpoobear at gmail.com
Mon May 3 10:27:08 CEST 2010


On Mon, May 3, 2010 at 1:49 AM, Stefan Behnel <stefan_ml at behnel.de> wrote:
>
> 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

And here if you wanted all the text on the line before the first '%'
as a list comprehension it would be something like this:

lines = [line[:line.index('%')] for line in lines if not
line.strip().startswith('%')]



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

What's this bizarre syntax?
I thought they changed for loop interations so that if you did
for line in open('packages.txt'):
    .... etc...

it would automatically close the file handle after the loop terminated.
Have I been wrong this whole time?

-Luke


More information about the Tutor mailing list