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.


On Oct 23, 2016 8:43 AM, "Steven D'Aprano" <steve@pearwood.info> wrote:
On Sun, Oct 23, 2016 at 08:37:07AM -0700, David Mertz wrote:
> Of course. But if you want last(), why not just spell the utility function
> as I did? I.e. as a function:
>
>     def last(it):
>          for item in it:
>              pass
>         return item
>
> That works fine for any iteratable (including a list, array, etc), whether
> or not it's a reduction/accumulation.

That's no good, because it consumes the iterator. Yes, you get
the last value, but you actually needed to do work on all the
previous values too.


--
Steve
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/