Backward for loop iteration in Python
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 listLand joins the elements a string with"n"between each element.[f for k, v in K]applies the function or statementfto each variablek, vin the list of key-value pairsK."%s=%s" % (k, v)is like sayingprintf("%s=%s",k,v)in another language.os.environ.items()says take the dictionary ofos.environ, and turn it into a list, where each element is a key-value pair