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

Brett Cannon brett at python.org
Thu Sep 27 01:02:03 CEST 2007

On 9/26/07, Terry Jones <terry at jon.es> wrote:
> What's the most compact way to repeatedly call a function on a list without
> accumulating the results?
> While I can accumulate results via
>     a = [f(x) for x in mylist]
> or with a generator, there doesn't seem to be a way to do this without
> accumulating the results. I guess I need to either use the above and ignore
> the result, or use
>     for x in mylist:
>         f(x)
> I run into this need quite frequently. If I write
>     [f(x) for x in mylist]
> with no assignment, will Python notice that I don't want the accumulated
> results and silently toss them for me?

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.


More information about the Python-ideas mailing list