pythonlistindexingmax

How can I manually (with an explicit loop) find the index of the maximum value in a list?


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?


Solution

  • 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