Wednesday, December 27, 2006

index of max value in a list PYTHON

the max function, it returns the maximum value in the
list rather than the index associated with that value.

How do I return the index?


l.index(max(l)

l.index(max(l)) will give you the index of the first occurrance of the
maximum.

m = max(l)
[ i for i,v in enumerate(l) if v==m ]

will give you a list of all indices where the max occurs. (Putting the
'max(l)' outside the list comprehension prevents it from being evaluated
for each loop element.)

3 comments:

fraka6 said...

You can use numpy to do it:
# transform to an array
import numpy
l = numpy.array(l)
idx = l.maxarg()

Benjamin said...

You can also do it in one line with:
idx = x.index(math.max(x))

Benjamin said...

You can also do it in one line with:
idx = l.index(math.max(l))