Skip to main content

Posts

Showing posts from August, 2008

Python: know when to be lazy

Lazy is good. One Python trend I've noticed quite a bit is the severe under-usage of generators. I often see list comprehension being used in situations where building a temporary list is not only wasteful, but more work. Example: print sum([x * 2 for x in something]) In this case, LC is being used to build a temporary list whose only purpose is to be iterated by "sum". Instead of constructing this list, why not pass an iterable object to "sum" and have it accumulate the sum from that? Well, not only can you, but it's even less to type (a whopping two characters less): print sum(x * 2 for x in something) Simply excluding the square brackets takes it from a list-comp to a generator expression, which is lazily evaluated. To demonstrate, proof that generators don't actually compute anything until they are pulled: def f(x): print x a = [f("LC") for x in xrange(10)] b = (f("GE") for x in xrange(10)) print "outside" b.next() p