What is a list compression in Python?

Stephen Hansen apt.shansen at gmail.com
Wed Jan 20 08:32:31 CET 2010

On Tue, Jan 19, 2010 at 10:39 PM, Rainer Grimm <r.grimm at science-computing.de
> wrote:

> Hallo,
> you can also look at list comprehension as syntactic sugar for the
> functions map and filter. The two functions from the functional world
> can be expressed in a comprehensive way with list comprehension.
> >>> [x**2 for x in range(10) ] == map ( lambda x: x*x, range(10))
> True
> >>> [ x for x in range(10) if x%2 == 0 ] == filter ( lambda x: x%2 == 0 ,
> range(10))
> True

I really don't think you can call comprehensions as mere syntactic sugar, as
there are measurable performance differences between the two. For something
to be syntactic sugar, it must be essentially equivalent. A list
comprehension is, IIUC, real syntactic sugar around a for loop. Meaning it,
in a real way, simply creates a for-loop with special syntax.

A list comprehension can be /equivalent in effect/ to the functions map and
filter, but it is not syntactic sugar. It is generating entirely different
code-paths with entirely different performance characteristics to achieve
the same goals. But that's not sugar.

Syntactic sugar is a sweet, cute, or cute way to express a more complex
thought in a simpler or more concise way. But the -effect- and -result- of
both thoughts are the same: if you do it manually, or with the sugar,
they're essentially equivalent. That's why its sugar... its just something
to make the experience sweeter, it doesn't -really- add any value beyond
making the experience sweeter.

Consider your tests:

>>> Timer("[x**2 for x in range(10) ]").timeit()
>>> Timer("map ( lambda x: x*x, range(10))").timeit()
>>> Timer("[ x for x in range(10) if x%2 == 0 ]").timeit()
>>> Timer("filter ( lambda x: x%2 == 0 , range(10))").timeit()

The list comprehension version performs distinctly better in each case.

The end result of the two are the same, but one is not sugar for the other.
A list comprehension is in essence a compact way of writing a for loop that
builds a list. A map (or filter) operation is a functional approach to build
a list: the difference is that the latter requires you to call a function a
lot, and function calls in Python are not cheap.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100119/038aecc7/attachment.html>

More information about the Python-list mailing list