On 2019-12-09 01:04, Steven D'Aprano wrote:
On Sun, Dec 08, 2019 at 10:37:51AM -0800, Guido van Rossum wrote:
We're not changing next(). It's too fundamental to change even subtly.

We might add itertools.first(), but not builtins.first(). This kind of
functionality is not fundamental but it's easy to get slightly wrong
(witness many hasty attempts in these threads).

What do you think of my suggestion that we promote the itertools recipe
"take" into a function?

https://mail.python.org/archives/list/python-ideas@python.org/message/O5RYM6ZDXEB3OAQT75IADT4YLXE25HTT/


I don't think that "first N items" is a case of YAGNI, because I
absolutely *have* needed it. In the past I've done this:

     items = list(items)
     # Pad with None to make sure that there are enough items.
     items.extend*[(None,)*(count-len(items))]
     items = iter(items)
     values = [next(items) for i in range(count)]


but using itertools is much better:

     values = take(count, items, default=None)

Using `take` is more reliable than repeated calls to `first`:

     values = [first(items, default=None) for i in range(count)]

due to the difference in behaviour when passed an iterator versus a
non-iterator iterable.

It's true that repeated calls to `take` will have the same issue, but
for the simple use-case of wanting the first N elements, including N=1,
`take` avoids needing an explicit loop and so avoids the surprising
difference between iterators and other iterables.

Why is the count first? Why not have the (definitely required) items first and let the count have a default of 1?
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/DC2UVPPWLCQUW4ZCKE2MI7H75AXLCQDF/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to