Building Lists the Hard Way in Python
Just for the record, these are dumb:
# Example A: reading
file = open(somefile)
contents = []
for line in file:
contents.append(line)
# Example B: writing
file = open(somefile, \"w\")
for line in contents:
file.writeline(line)
# Example C: filtering
result = []
for line in contents:
if not line.find(\"boo\"):
result.append(line)
Python is easy. That means you should just about always be able to get the same results with a lot less effort. Python is not Java.
# Example A: reading contents = open(somefile).readlines() # Example B: writing open(somefile,\"w\").writelines(contents) # Example C: filtering result = [ line for line in contents if not line.find(\"boo\") ] # Example D: In case you miss confusing, obfuscated, ugly code since you started using python open(somefile,\"w\").writelines( [ line for line in open(otherfile) if not line.find(\"boo\") ])
By the way, example D is also stupid. Nobody should write code like that. Python is not Perl.



Example C isn’t so dumb.
Although I prefer the second C, The first C is not so bad.
- Paddy.
Comment by Paddy3118 — 2008-April-18 @ 05:14
Yeah, it’s not totally horrible, but you will be happier with the smarter, smaller version.
Terseness is not a value if it hurts readability or is particularly idiomatic.
Still, you should never write more code than you need to, especially if readability is roughly the same. Longer version are more likely to be wrong, more likely to be understood, slower to read. Longer code can be less efficient than the behaviors the language is optimized for like list comprehensions, some iterator behaviors, and some string handling features.
In general, writing something in primitives that already has a well-studied and well-considered implementation in the language is a losing game.
Comment by Tim — 2008-April-21 @ 03:23