It really ius frustrating how often we repeat entire conversations on this list :-(
But last time, one of the use cases was "get a random item from a dict", and there really is not a terribly easy (and efficient) way to do that now.
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.
NOTE: I actually use this as a teaching moment in my intro to Python class: we have an assignment where there is a need to grab an arbitrary (not necessarily random) item from a dict (without removing it). most students come up with something like:
random.choice(list(the_dict.items()))
which works fine for any but the largest of dicts, but is not an optimum solution.
I don't think anyone has ever come up with next(iter(the_dict.items)) on their own.
So I have a little lesson where I run through the options, and use it as a chance to introduce the iterator protocol. So it's a good teaching moment, but not a great example of how Python usually has an easy and obvious way to do seemingly simple operations.
-CHB
Christopher Barker, PhD (Chris)
Python Language Consulting
- Teaching
- Scientific Software Development
- Desktop GUI and Web Development
- wxPython, numpy, scipy, Cython