[Python-ideas] Calling a function of a list without accumulating results
Stephen J. Turnbull
stephen at xemacs.org
Thu Sep 27 07:15:23 CEST 2007
Terry Jones writes:
> The trivial case I posted isn't much of a win over the simple 2-line
> alternative, but it's easy to go to further:
> f(x, y) for x in myXlist for y in myYlist
> instead of
> for x in myXlist:
> for y in myYlist:
> f(x, y)
Oh, is that what you meant?!<wink>
I think the second version is much more readable, and only a few
characters longer when typing.
> The second argument is one of consistency. If list comprehensions are
> regarded as more pythonic and the Right Way to code in Python, I'd make the
> same argument for when you don't happen to want to keep the accumulated
> results. Why force programmers to use two coding styles in order to get
> essentially the same thing done?
Because it is essentially not the same thing. Comprehension syntax is
justified precisely when you want to generate a list value for immediate
use, and all the other ways to generate that value force you to hide
what's being done in an assignment deep inside a thicket of syntax.
List comprehensions are Pythonic because they "look like" lists.
OTOH, in Python, control syntax always starts with a keyword. A naked
comprehension just doesn't look like a control statement to me, it
still looks like an expression. I don't know if that's un-Pythonic,
but I do like the multiline version better.
> I think these are decent arguments. It's simply the full succinctness and
> convenience of list comprehensions, without needing to accumulate results.
But succintness and convenience aren't arguments for doing something
in Python as I understand it. Lack of succintness and convenience may
postpone acceptance of a PEP, or even kill it, of course. But they've
never been sufficient for acceptance of a PEP that I've seen.
More information about the Python-ideas