List comprehensions can help your programming

More *sometimes* better


The source code, as it reached me, was something I'll simplify for ease in explanation as

    if status == "status1":
        print '<a href = "link1">' + explanation1 + '</a>'
        print '<br />'
        print '<a href = "link2">' + explanation2 + '</a>'
        print '<br />'
    if status == "status2":
        print '<a href = "link2">' + explanation2 + '</a>'
    if ...

The code went on for pages. Here's one reduction I made (again, approximately--I leave aside certain issues not pertinent to this discussion):

    description2 = ("link2", "explanation2")
    description_list['status1'] = [('link1', 'explanation1'), description2, ...]
    description_list['status2'] = [description2]
    print "<br />".join(["<a href = '%s'>%s</a>" % pair for pair in description_list[status]])

Do I truly think that rather obscure one-liner is easier to read than the utterly elementary sequence of if-s and print-s? Yes: in the first place, the change reduced the line-count by about half. More telling, a handful of typographical errors were actually present in the original, but no one had noticed in all the lines of quotes and other punctuation. Now the hyperlink formula appears in just one place, and it's far easier to correct.

My conclusion: comprehensions are good for more than just a couple of extra points on a test.

Take it farther

One of the great features of Python, and coincidentally JavaScript and XPath, two other languages which support comprehensions, is that you can start useful coding with a small investment: you don't have to learn all of Python to begin to code effectively. Don't mistake that, though, for an excuse to stop learning. While nearly all languages have obscure features, best left to experts and/or rare situations, comprehensions aren't among them. Comprehensions are good ways to express code that arises in many common situations. Be on the look-out for opportunities where they can help you.

Van Rossum wrote about functional influences on Python earlier this year.

Join us:






Answers - Powered by ITworld

Ask a Question