[Python-ideas] Proposal: A Reduce-Map Comprehension and a "last" builtin

Tim Peters tim.peters at gmail.com
Fri May 25 14:14:04 EDT 2018


[Peter O'Connor]
>> ...
>> We could use given for both the in-loop variable update and the variable
>> initialization:
>>    smooth_signal =  [average given average=(1-decay)*average + decay*x
>>                                 for x in signal] given average=0.

[Steven D'Aprano <steve at pearwood.info>]
> I don't think that will work under Nick's proposal, as Nick does not
> want assignments inside the comprehension to be local to the surrounding
> scope. (Nick, please correct me if I'm wrong.)

Nick appears to have moved on from "given" to more-general augmented
assignment expressions.  See PEP 577, but note that it's still a
work-in-progress:

    https://github.com/python/peps/pull/665


Under that PEP,

    average = 0
    smooth_signal =  [(average := (1-decay)*average + decay*x)
                                 for x in signal]

Or, for the running sums example:

    total = 0
    sums = [(total += x) for x in data]

I'm not entirely clear on whether the "extra" parens are needed, so
added 'em anyway to make grouping clear.


More information about the Python-ideas mailing list