[Python-ideas] Calling a function of a list without accumulating results

Terry Jones terry at jon.es
Thu Sep 27 01:20:06 CEST 2007


Hi Brett & Adam

Thanks for the replies.

| Only after the list is completely constructed.  List comprehensions
| are literally 'for' loops with an append call to a method so without
| extending the peepholer to notice this case and strip out the list
| creation and appending it is not optimized.
| 
| > A possible syntax change would be to allow the unadorned
| >
| >     f(x) for x in mylist
| >
| > And raise an error if someone tries to assign to this.
| 
| Go with the 'for' loop as Adam suggested.  I just don't see this as
| needing syntax support.

I think there are two arguments in its favor.

The first is the same as one of the arguments for providing list
comprehensions and generator expressions - because it makes common
multi-line boilerplate much more concise.

There's a certain syntax that's allowed in [] and () to make list
comprehensions and generator expressions. I'm suggesting allowing exactly
the same thing, but with no explicit grouping wrapped around it.

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)

and of course there are many more examples.

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?

I think these are decent arguments. It's simply the full succinctness and
convenience of list comprehensions, without needing to accumulate results.

Thanks again for the replies. Changing the peepholer to notice when there's
no assignment to a list expression would also be nice. I'd look at it if I
had time..... :-)

Terry



More information about the Python-ideas mailing list