Skip to content Skip to sidebar Skip to footer

Locate The Index Of Largest Value In An Array Python

How would I locate the index of the largest value in an array that the user inputs? Here is what I have: def main(): numbers = eval(input('Give me an array of numbers: ')) la

Solution 1:

max_index, max_value = max(enumerate(numbers), key=lambda pair: pair[1])

This does:

  • enumerate(numbers) generates (index, value) pairs
  • lambda pair: pair[1] takes such a pair and returns the value part of it
  • max() returns the max pair out enumerate(numbers), doing the comparison using the values from the key function

Solution 2:

Try this:

ind = numbers.index(max(numbers))

Solution 3:

defmain():
   numbers = eval(input("Give me an array of numbers: "))
   indices = [i for i, x inenumerate(my_list) if x == max(numbers)]
   return indices

Runs as:

>>>indices = main()
Give me an array of numbers: [1, 5, 9, 3, 2, 9]
>>>indices
[2, 5]

This code uses list comprehension to loop over the list and see where the maximum value(s) are using max(). This also accounts for the fact that there might be more than one of the maximum value, e.g. [1, 5, 9, 3, 2, 9], 9 appears twice.

Post a Comment for "Locate The Index Of Largest Value In An Array Python"