List comprehensions can help your programming

More *sometimes* better

By  

'Know what a "list comprehension" is?

Odds are, you do--but that's a different thing from using it, and using it well might be in a third category. Let's look at a couple of specific examples, and see what they teach.

Modern history

Code for this example will be in Python; I was reading Python sources when I began this note. Lots of modern languages have comprehensions (sometimes list comprehensions, but also comprehensions over sets, dictionaries, generators, and other types), especially those from the functional wing. The first widely-used language to use "comprehension" for the construct was Miranda.

This is intriguing, as Python has generally distanced itself from functional styles in recent years. Python author Guido van Rossum has quite deliberately chosen to incorporate more than one kind of comprehension in Python, though, at the same time as he strives to reduce the complexity of the language in other ways. What's the big deal?

My own experience chatting with programmers is that many confidently explain comprehensions with an example such a [x * x for x in range(10)]: "that lists the first ten squares, [0, 1, 4, ..., 81]". They're right.

What's the point of that, though? Many seem to regard it as an academic footnote, no more practical than, well, a list of squares.

On another hand, how often have you done something like this?

    big_list = f1()
    list_that_matters = []
    for item in big_list:
        if important_today(item):
            list_that_matters.append(f2(item))

followed by sorting list_that_matters, or passing it to another function, or so on. Since 2.0 of Python, however, you can also write this as list_that_matters = [f2(item) for item in f1() if important_today(item)]. Is the latter better? Fitting on a single line isn't a win if it hurts readability; in this case, though, yes, I think the list comprehension is generally likely to get the point across more effectively to the maintainer who next picks up this fragment two years in the future. Moreover, as piman explains in more detail, list comprehensions also have the potential to help with performance.

A matter of style

I just came across an example "in the wild" that made me think of the expressivity of comprehensions.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question