On Tue, Jan 19, 2010 at 10:39 PM, Rainer Grimm <span dir="ltr"><<a href="mailto:r.grimm@science-computing.de">r.grimm@science-computing.de</a>></span> wrote:<br><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">

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

<div><br></div><div>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.</div>

<div><br></div><div>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.</div>

<div><br></div><div>Consider your tests:</div><div><br></div><div><div>>>> Timer("[x**2 for x in range(10) ]").timeit()</div><div>3.4986340999603271</div><div>>>> Timer("map ( lambda x: x*x, range(10))").timeit()</div>

<div>4.5014309883117676</div><div>>>> Timer("[ x for x in range(10) if x%2 == 0 ]").timeit()</div><div>3.3268649578094482</div><div>>>> Timer("filter ( lambda x: x%2 == 0 , range(10))").timeit()</div>

<div>5.3649170398712158</div><div><br></div><div>The list comprehension version performs distinctly better in each case.</div><div><br></div><div>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. </div>

</div></div><br clear="all"><div name="mailplane_signature">--S</div>