This post originated from an RSS feed registered with Python Buzz
by Thomas Guest.
Original Post: Are List Comprehensions the Wrong Way Round?
Feed Title: Word Aligned: Category Python
Feed URL: http://feeds.feedburner.com/WordAlignedCategoryPython
Feed Description: Dynamic languages in general. Python in particular. The adventures of a space sensitive programmer.
Let’s suppose you’re the director of a large art gallery and another
art gallery wants to know if it can loan one of your Picassos for a
special exhibition. First, you’re going to need to make a list of all
your Picassos – which means someone visiting each room in the gallery,
looking in all the artworks in that room and noting down the ones by
Picasso.
Python provides a couple of ways to model this problem. You can use
explicit loops or list comprehensions.
Up until Python 2.0, this was the only approach to coding the
algorithm. It reads as a top-down approach and probably expresses the
way you (you’re the gallery director, remember?) would address the
problem:
I give someone a pen and a blank piece of paper (that’s the list())
tell them to visit each room in the gallery (that’s the for room in gallery:)
and to look at each artwork in the room (for artwork in room:)
and, if that artwork is by Picasso, add it to the list (if artwork.is_picasso(): picassos.append(artwork))
By the way, I use the term artwork and not painting since Picasso was
a painter, sculptor, printmaker and ceramicist.
List Comprehensions
Python 2.0 introduced list comprehensions – a neat way of building
lists from lists (or indeed any other iterable). This reverses the
algorithm, putting it from the point-of-view of the someone who tours
the gallery and makes the list. That someone’s task focuses
on the artwork:
One of the things I like about Python is that you don’t often need to
squint at the documentation to clear up matters of syntax. Things
tend to work the way you expect them to. It’s pretty much the reverse
of C++ where you continually get the sense that you’re persuading the
compiler you’re talking the same language.
In this particular case, I suppose it’s easy enough to remember how to
get things right (write the explicit loop you’d need for a top-down
solution, shift the inner-most expression to the front, put the whole
thing in square backets) but it still seems wrong to me. To me wrong
it still seems but.