19
def main():
    a = [2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]
    max = 0
    for number in a:
        if number > max:
            max = number
    print max

if __name__ == '__main__':
    main()

I am able to get the maximum value in the array (without using max() of course...). How can I get the index (position) of that value? Please try to keep it simple without using new Python key words or built-in functions. Thanks!

8
  • duplicate of stackoverflow.com/questions/3989016/… ? Jul 17, 2012 at 21:03
  • 1
    “without using max() of course” – I did understand that correctly, you don’t want to use the built-in function, right?
    – poke
    Jul 17, 2012 at 21:07
  • Yeah, I was hoping for an answer like Recursed's below. I'm trying to learn programming the hard way first before I can use the built-in functions ;) Jul 17, 2012 at 21:10
  • 1
    It also depends on the definition of "built-in functions", as (for instance) if number > max could be considered using the builtin method __gt__ of the built-in type list :) Seriously though - why can't you just use the built-in max - just an intellectual exercise or self-torture? Jul 17, 2012 at 21:12
  • 2
    So, am I right in thinking that you're aware that max is the correct, concise and efficient method for this in Python, but you're after ways of how not to do it? Jul 17, 2012 at 21:17

9 Answers 9

28

In my code I would use this:

>>> max(enumerate(a),key=lambda x: x[1])[0]
3
2
  • 8
    Alternatively, max(range(len(a)), key=lambda i: a[i]) Jul 17, 2012 at 21:29
  • 1
    Or even: max(zip(a, range(len(a)))[1] although if two elements are equal, this will return the element with the highest index, while yours will return the element with the lowest index. Jul 17, 2012 at 22:08
22

A simple one liner of:

max( (v, i) for i, v in enumerate(a) )[1]

This avoids having to .index() the list after.

1
  • 4
    As a note, if the list has duplicates, this will return the largest index at which the max element resides. (5,3) < (5,4) returns True Jul 17, 2012 at 21:11
9

Update:

max_idx = -1
max_val = a[0]
for i in xrange(1, len(a)):
    if a[i] > max_val:
        max_val = a[i]
        max_idx = i

This doesn't shadow built-in function max(), and also will give correct answers for lists that consist of only negative values.


Previous solution

a.index(max(a))

will do the trick.

Built-in function max(a) will find the maximum value in your list a, and list function index(v) will find the index of value v in your list. By combining them, you get what you are looking for, in this case the index value 3.

Note that .index() will find the index of the first item in the list that matches, so if you had several identical "max" values, the index returned would be the one for the first.

For more information:

In the spirit of "Simple is better than complex." (Zen of Python)

1
  • 1
    @ShankarKumar Sorry, I read your question too quickly initially, I updated my answer just FYI.
    – Levon
    Jul 17, 2012 at 21:30
8

If you aren't allowed to use the built in index() function, just iterate with an index, instead of using a foreach loop.

for i in range(len(a)):
    if a[i] > max:
        max = a[i]
        maxIndex = i
9
  • Thanks, this was what I was looking for. Something that didn't use any built-in functions! :) Jul 17, 2012 at 21:16
  • 7
    @ShankarKumar Being a pedant range and len are builtin functions :) Jul 17, 2012 at 21:19
  • I might use enumerate, instead of range. Jul 17, 2012 at 21:21
  • 1
    This shadows built-in function max (which may not be a problem since we aren't suppose to use it .. :-) but probably not good practice, and wouldn't work correctly for lists that only contain negative values
    – Levon
    Jul 17, 2012 at 21:26
  • 3
    @Levon You shouldn't assign max to zero before the list anyway, you should set it to the first item in the list.
    – Rob Wagner
    Jul 18, 2012 at 0:44
5

Use the argmax method of the numpy.array object.

import numpy as np
np.array(a).argmax()
1

You can use enumerate to also give you an index while iterating through a list:

>>> a = [2, 1, 5, 234, 3, 44, 7, 6, 4, 5, 9, 11, 12, 14, 13]
>>> maxIndex, maxNumber = 0, 0
>>> for index, number in enumerate(a):
        if number > maxNumber:
            maxIndex = index
            maxNumber = number

>>> maxIndex, maxNumber
(3, 234)
0

Use the index(x) function. See the documentation here http://docs.python.org/tutorial/datastructures.html

def main():
    a = [2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]
    max = 0
    for number in a:
        if number > max:
            max = number
    max_index = a.index(max)
    print max

However, this is not as fast as other suggested answers (e.g. using enumerate). Simple though.

0

this is way simpler

x.index(max(x)) #where x is your list
1
-3

If you like powerfull code you would like this :) If you just have integer numbers you can substitute float by int.

maximum= max(map(float,[2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]))

If you have your input in a text file do this:

file.txt

2 1 5 234 3 44 7 6 4 5 9 11 12 14 13

maximum= max(map(float,(open('file.txt', 'r').readline()).split()))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.