[Python-ideas] Reduce/fold and scan with generator expressions and comprehensions

Steven D'Aprano steve at pearwood.info
Sun Oct 23 19:22:32 EDT 2016


On Sun, Oct 23, 2016 at 08:47:12AM -0700, David Mertz wrote:
> Consuming the iterator is *necessary* to get the last item. There's no way
> around that.
> 
> Obviously, you could itertools.tee() it first if you don't mind the cache
> space. But there cannot be a generic "jump to the end" of an iterator
> without being destructive.

Right. But you're missing the point of Danilo's proposal. He isn't 
asking for a function to "jump to the end" of an iterator. Look at his 
example. The word "last" is a misnomer: he seems to me talking 
about having a special variable in comprehensions that holds the 
*previous* value of the loop variable, with special syntax to set its 
FIRST value, before the loop is entered. So "last" is a misleading name, 
unless you understand it as "last seen" rather than "very last, at the 
end".

So given an iterator [1, 2, 4, 8], and an initial value of -1, we would 
see something like this:

[(previous, this) for this in [1, 2, 4, 8] with previous as -1]
# or some other syntax

returns:

[(-1, 1), (1, 2), (2, 4), (4, 8)]

So a dedicated function that does nothing but scan to the end of the 
iterator and return the last/final value seen is no alternative to his 
proposal.



-- 
Steve


More information about the Python-ideas mailing list