breadth first search

Scott David Daniels scott.daniels at acm.org
Wed Feb 8 12:21:46 EST 2006


Chris McDonough wrote:
> News wrote:
>...   Can Python
>> create list dynamically, I want to implement a program which will read 
>> data
>> from a file and store each line into a list, is this possible?
> 
> L = []
> [L.append(line) for line in (open('filename.txt')]
> 
> - C
Woops, crossed wires there:
after:
     somefile = open('filename.txt')

You can do:
     L = somefile.readlines()
or
     L = [line for line in somefile]
or
     L = []
     for line for line in somefile:
         L.append(line)
to put all lines of somefile into L,

but
     L = []
     K = [L.append(line) for line in somefile]
builds a list K that has a None for each line in
somefile, while filling up L with the lines as a side-effect.
It is a style to avoid.  Dropping the "K = " part simply says
"build the list of Nones and then discard it." -- not good style.

Also, it is good style to then call somefile.close() after
you are done with the file.

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list