pythonian way

Alan Daniels daniels at mindspring.com
Sat Feb 26 00:02:28 EST 2000


On Fri, 25 Feb 2000 08:33:15 +0100, the infinitely wise Milos Prudek
(prudek at nembv.cz) spoke forth to us, saying...

[snip...]
>The following excerpt works. It reads lines from config file. But I
>would like to ask if it is 'right' in the Pythonian way.


>A=[]
>Line=H.readline()
>while Line<>'':
>	if Line<>'' and Line<>'\n':
>		A.append(Line)
>	Line=H.readline()

I myself would use:

A = []
for Line in H.readlines():
    if Line not in ("", "\n"):
        A.append(Line)

Pretty much in the same spirit, but with a couple of minor shortcuts
(see, isn't Python intuitive? A newbie writes code almost identical to
a expert's on the first try!(<BIG self-mocking wink>).

First shortcut, H.readlines() to slurp all the lines out of the file
at once and store them as a list, and then iterate through these with
the "for" statement. One less line of code, but since it reads in all
the lines at once, you obviously don't want to do this for any really
gigantic files.

Next trick, using the "not in" to match the Line variable to one of a
list of possible strings. This way of checking if something is/is not
in a sequence works for both lists and tuples. And yeah, it looks
goofy for only two items ("" and "\n"), but imagine it being more
useful for *lots* of items or (gasp!) even building such a list on the
fly...

Hope this helps. To others, if I'm giving bad advice, please shoot me
down. I'm trying to stick with what I know for the moment. :=)

Wading-into-the-advise-waters-one-step-at-a-time'ingly yours, Alan.

-- 
=======================
Alan Daniels
daniels at mindspring.com
daniels at cc.gatech.edu



More information about the Python-list mailing list