[Tutor] Iterating through a list of strings

Stefan Behnel stefan_ml at behnel.de
Mon May 3 10:50:41 CEST 2010


Luke Paireepinart, 03.05.2010 10:27:
> On Mon, May 3, 2010 at 1:49 AM, Stefan Behnel 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('%')]

Readability counts, though. And I assumed that the OP wanted the package 
name, without any potentially surrounding whitespace.


>>     with open('packages.txt') as f:
>>         for package_name in read_package_names(f):
>>             print package_name
>
> What's this bizarre syntax?

Look it up in the docs, it's called "with statement". Its purpose here is 
to make sure the file is closed after the execution of the statement's 
body, regardless of any errors that may occur while running the loop.


> 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?

Yes. The fact that the file is automatically closed after the loop is an 
implementation detail of CPython that does not apply in other Python 
implementations.

Stefan



More information about the Tutor mailing list