philihpAboutPGPLightning

Backward for loop iteration in Python

Philihp Busby,0 min read

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

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:

GitHub · Bluesky · LinkedIn · Instagram · KeybaseRSS

Built from 8f0906ac CC BY 4.0 — with love from San Francisco.