On Fri, Oct 08, 2021 at 01:42:35PM -0700, Christopher Barker wrote:
Anyway, I do see the benefit of adding first() to itertools -- there really is a key problem with:
next(iter(an_iterable))
for newbies -- you can get really really far in Python without ever having to call either next() or iter(). Sure, if it's a recipe, people can use it without really understanding it, but having an easy and obvious solution would be nice.
Yes? How does that make it a *problem*? I disagree strongly that needing to learn a simple, basic technique is a problem to be solved. Let's take a simple example: the successor of a Unicode character e.g. B follows A, ρ (rho) follows π (pi). https://stackoverflow.com/questions/2673360/most-efficient-way-to-get-next-l... The obvious solution is: chr(ord(c)+1) but perhaps not so obvious to newbies. We can get very far without learning about ord() and chr(), so perhaps we need a string method `nextchar()` so that newbies don't get confused by the complexities of addition, ord() and chr(). Perhaps not. Programming is about composing functionality. I think it is fine to just teach them to use ord() and chr(). Not every one-liner needs to be a builtin, or even a named function in the stdlib. I think the same applies to `first()` and `last()`. Just learn to compose the existing functionality. The beauty of *teaching people to fish* instead of just handing them a fish is that they can then decide for themselves how to handle this. If their iterable is already an iterator, they can save one function call by dropping the call to iter() and just calling next() directly. If they want the second item as well, they can call next() a second time. If they want a default value when the iterable is empty, they can provide a default to the next() call. Instead of a fairly trivial named function that probably nobody is going to use in practice, it becomes a learning moment. Honestly, it really isn't clear that *anyone* would use these functions in practice. Especially if you already know you have an iterator, it is easier to just write a = next(myiterator) than to do this: # scroll to the top of the module, where the imports live from itertools import first # scroll back to where you were working a = first(myiterator) Newbies won't know first() lives in itertools, and those experienced enough to know it is there probably won't bother to use it. -- Steve