23

I am able to get the maximum value in the array with an explicit loop:

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()

How can I get the index (position) of that value?

Karl Knechtel
61.4k14 gold badges131 silver badges193 bronze badges
asked Jul 17, 2012 at 21:00
8
  • 1
    "without using max() of course" – I did understand that correctly, you don’t want to use the built-in function, right? Commented 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 ;) Commented 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? Commented Jul 17, 2012 at 21:12
  • Yeah, I'm just a beginner trying to become a "smarter" programmer! Commented Jul 17, 2012 at 21:14
  • 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? Commented Jul 17, 2012 at 21:17

9 Answers 9

30

In my code I would use this:

>>> max(enumerate(a),key=lambda x: x[1])[0]
3
answered Jul 17, 2012 at 21:15
Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively, max(range(len(a)), key=lambda i: a[i])
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.
23

A simple one liner of:

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

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

answered Jul 17, 2012 at 21:02

3 Comments

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
@inspectorG4dget I think this can be amended by making the index negative.
@JonClements The downside of this is unnecessary comparisons of indices if the same value occurs several times consecutively in an ascending sequence. e.g. 1, 3, 3, 3, 5 would compare i 1 < 2 and 2 < 3, although we'd only need to keep track of the current max value's index instead of comparing anything.
12

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)

answered Jul 17, 2012 at 21:01

2 Comments

@ShankarKumar Sorry, I read your question too quickly initially, I updated my answer just FYI.
I am not dealing with negative numbers in my scenario, your previous solution is a perfect and simple solution.
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
answered Jul 17, 2012 at 21:04

9 Comments

Thanks, this was what I was looking for. Something that didn't use any built-in functions! :)
@ShankarKumar Being a pedant range and len are builtin functions :)
I might use enumerate, instead of range.
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 You shouldn't assign max to zero before the list anyway, you should set it to the first item in the list.
|
6

Use the argmax method of the numpy.array object.

import numpy as np
np.array(a).argmax()
answered Oct 1, 2014 at 14:05

Comments

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)
answered Jul 17, 2012 at 21:04

Comments

1

this is way simpler

x.index(max(x)) #where x is your list
answered May 16, 2017 at 13:59

1 Comment

The OP specifically said without using max().
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.

answered Jul 17, 2012 at 21:03

Comments

-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()))

answered Apr 1, 2013 at 4:33

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.