argmax

George Sakkis george.sakkis at gmail.com
Thu Jun 1 11:40:23 EDT 2006


David Isaac wrote:

> 1. Why is there no argmax built-in?
> (This would return the index of the largest element in a sequence.)

I guess because it's not used frequently enough. I've needed
argmax/argmin more than once though, so I would welcome them as
builtins.

> 2. Is this a good argmax (as long as I know the iterable is finite)?
> def argmax(iterable): return max(izip( iterable, count() ))[1]

Yes, it's ok. Here's another one that doesn't require importing
itertools:
def argmax(iterable): return max((x,i) for i,x in
enumerate(iterable))[1]

> 3. If this is the only place in a module where I need count and izip,
> should I import them at the module level or at the level of the function?
> What are the considerations here?

Both have their merits. I like having the imports close to the point
they're used, at least if used only once; OTOH having all imports at
the top of the module makes easier to see the module's dependencies
without grep'ing for import (that's especially useful for non-standard
imported modules or new additions ot the std lib if backwards
compatibility is an issue).

George




More information about the Python-list mailing list