I have seen the code in heapq.nlargest()
of Python standardlib as following:
if n == 1:
it = iter(iterable)
sentinel = object()
if key is None:
result = max(it, default=sentinel)
else:
result = max(it, default=sentinel, key=key)
return [] if result is sentinel else [result]
It convert iterable
to it
by iter()
first, and then to get maximum value from it
by max()
function passed argument it
.
Why don't just use iterable object? Are there any advantage I have no awareness?