Blogging Ottinger (tim)

2008-April-18

Building Lists the Hard Way in Python

Filed under: Programming, Life

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.

2 Comments »

The URI to TrackBack this entry is: http://tottinge.blogsome.com/2008/04/18/building-lists-the-hard-way-in-python/trackback/

  1. 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

  2. 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

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.

Get free blog up and running in minutes with Blogsome
Theme designed by Jay of onefinejay.com