user2238548
user2238548

Reputation: 11

Index of the max element of a list?

So I need to write and test a function that returns the index of the largest element in the list (or, if several elements have he largest value, the index of the first one of them) and I'm not allowed to use the max function.

def largestElementIndex(lst):
    x=0
    maxNum=0
    while x+1 < len(lst):
        if lst[x] > maxNum:
            maxNum=x
        x+=1
    return maxNum

print "Program Output"
indexOfMax = largestElementIndex([1, 4, 3, 3, 2])
print 'Index Of Max Value is',indexOfMax

Upvotes: 1

Views: 953

Answers (2)

vivek
vivek

Reputation: 2867

You can also use this simple approach if you don't want to use max function:

res = lst.index(sorted(lst)[-1])

cheers!

Upvotes: 1

Blender
Blender

Reputation: 298126

You need to store the largest number as well as the index:

def largestElementIndex(lst):
    x=0
    maxNum=0
    maxIndex=0

    while x < len(lst):
        if lst[x] > maxNum:
            maxIndex=x
            maxNum=lst[x]
        x+=1
    return maxIndex

I'd also use a for loop:

def largestElementIndex(lst):
    max_index = 0
    max_value = lst[0]

    for index, value in enumerate(lst)
        if value > max_value:
            max_index = index
            max_value = value

    return max_index

To do this with max, you use enumerate the same way:

max_index = max(enumerate(lst), key=lambda pair: pair[1])[0]

Upvotes: 5

Related Questions