So lately I've been hacking up Python on the self imposed restriction of running everything on a 450 MHz Pentium II. This way if I ever do anything less-than-optimal, it's immediately obvious, and I don't learn any bad habits.

Then I came across the following optimization.

>>> import os
>>> for k, v in os.environ.items():
... print "%s=%s" % (k, v)

Pretty direct, right? Iterate through the os.environ hash, and print every key/value pair. But Diveintopython.org showed me I can do better using List Comprehensions.

>>> print "n".join(["%s=%s" % (k, v) for k, v in os.environ.items()])

This is better, because it builds the string first, then calls print once. Neat!

It works like this:

  • "n".join(L) takes the list L and joins the elements a string with "n" between each element.
  • [f for k, v in K] applies the function or statement f to each variable k, v in the list of key-value pairs K.
  • "%s=%s" % (k, v) is like saying printf("%s=%s",k,v) in another language.
  • os.environ.items() says take the dictionary of os.environ, and turn it into a list, where each element is a key-value pair