21
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!

Levon
  • 138,105
  • 33
  • 200
  • 191
Shankar Kumar
  • 2,197
  • 6
  • 25
  • 32
  • duplicate of http://stackoverflow.com/questions/3989016/how-to-find-positions-of-the-list-maximum ? – Andre Holzner Jul 17 '12 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 '12 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 ;) – Shankar Kumar Jul 17 '12 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? – Jon Clements Jul 17 '12 at 21:12
  • Yeah, I'm just a beginner trying to become a "smarter" programmer! – Shankar Kumar Jul 17 '12 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*? – Jon Clements Jul 17 '12 at 21:17
  • Right. But I would call it a way that needs a little more brain power, no? – Shankar Kumar Jul 17 '12 at 21:19
  • As others have pointed out, your question relies on a fundamental assumption that there *is* only a single point equal to the maximum value. For many types of data, that's incorrect. Be sure to choose an output data structure that accommodates multiple simultaneously correct answers. – abought Jul 17 '12 at 21:56

9 Answers9

28

In my code I would use this:

>>> max(enumerate(a),key=lambda x: x[1])[0]
3
ovgolovin
  • 13,063
  • 6
  • 47
  • 78
  • 8
    Alternatively, `max(range(len(a)), key=lambda i: a[i])` – Andrew Clark Jul 17 '12 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. – Joel Cornett Jul 17 '12 at 22:08
23

A simple one liner of:

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

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

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • 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` – inspectorG4dget Jul 17 '12 at 21:11
10

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)

Levon
  • 138,105
  • 33
  • 200
  • 191
  • 1
    @ShankarKumar Sorry, I read your question too quickly initially, I updated my answer just FYI. – Levon Jul 17 '12 at 21:30
  • 1
    I am not dealing with negative numbers in my scenario, your previous solution is a perfect and simple solution. – Wayne Workman May 28 '23 at 04:46
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
Rob Wagner
  • 4,391
  • 15
  • 24
  • Thanks, this was what I was looking for. Something that didn't use any built-in functions! :) – Shankar Kumar Jul 17 '12 at 21:16
  • 7
    @ShankarKumar Being a pedant `range` and `len` are builtin functions :) – Jon Clements Jul 17 '12 at 21:19
  • I might use enumerate, instead of range. – Joel Cornett Jul 17 '12 at 21:21
  • line 2: `max` referenced before assignment – inspectorG4dget Jul 17 '12 at 21:21
  • @JonClements is right, I thought you we're doing it this way because a teacher wouldn't let you use `index()` or something. If you can use it, there are way better ways to do this, and as long as you understand it, there's no reason not to use the handy functions. – Rob Wagner Jul 17 '12 at 21:21
  • @Recursed I realize I'm doing it the hard way, but no this isn't homework. I'm trying to teach myself Python this summer, and I'm exploring many options of achieving desired outputs.. – Shankar Kumar Jul 17 '12 at 21:26
  • 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 '12 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 '12 at 00:44
  • @Recursed Yes, I'm pretty sure I already know that since my code already does this correctly .. :) – Levon Jul 18 '12 at 05:32
5

Use the argmax method of the numpy.array object.

import numpy as np
np.array(a).argmax()
AlexP
  • 86
  • 1
  • 4
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)
poke
  • 369,085
  • 72
  • 557
  • 602
1

this is way simpler

x.index(max(x)) #where x is your list
Mohamed Emad
  • 123
  • 1
  • 14
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.

MoRe
  • 1,478
  • 13
  • 25
-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()))

Community
  • 1
  • 1
Carlos Neves
  • 67
  • 1
  • 2