How to Find the Maximum Value in an Array in Python (and Its Index)

To find the maximum value in an array in Python, call max(values) on a list or arr.max() on a NumPy array. To get the index of the maximum value, use values.index(max(values)) for a list or np.argmax(arr) for NumPy. This guide covers both, plus all indices when the maximum appears more than once, the maximum per row and column of a 2D array, NaN values, empty arrays and the maximum by a key.

All examples were run with Python 3.12.5 and NumPy 2.5.3 in the Windows Command Prompt. Reference: max() in the Python docs and numpy.argmax.

Maximum value and its index

import numpy as np

temps = [21.5, 24.1, 19.8, 26.3, 22.7]
print("list max:", max(temps))                   # built-in max()
print("index of max:", temps.index(max(temps)))  # position of the largest value

arr = np.array(temps)
print("NumPy max:", arr.max())                    # same as np.max(arr)
print("NumPy argmax:", arr.argmax())              # index of the largest value

Output:

list max: 26.3
index of max: 3
NumPy max: 26.3
NumPy argmax: 3

Index of the maximum value: five ways

import numpy as np

sales = [310, 450, 290, 450, 380]

print(sales.index(max(sales)))                              # 1. index(max()): first match
print(max(range(len(sales)), key=sales.__getitem__))        # 2. one pass with a key
print(max(enumerate(sales), key=lambda pair: pair[1]))      # 3. (index, value) together
print(int(np.argmax(sales)))                                # 4. NumPy argmax: first match
print(np.flatnonzero(np.array(sales) == max(sales)))        # 5. ALL indices of the max

Output:

1
1
(1, 450)
1
[1 3]
Command Prompt output of five ways to find the index of the maximum value in a Python list including index(max()), enumerate, argmax and all indices
When the maximum appears twice (450), most methods return the first position; np.flatnonzero returns all of them.
MethodReturnsNotes
lst.index(max(lst))First indexSimple; scans the list twice
max(range(len(lst)), key=lst.__getitem__)First indexOne pass
max(enumerate(lst), key=...)(index, value)Both at once
np.argmax(arr)First indexFastest for large data
np.flatnonzero(arr == arr.max())All indicesHandles ties

Maximum of a 2D array (per row and per column)

Pass axis=0 for the maximum of each column and axis=1 for each row. argmax() without an axis returns a position in the flattened array; convert it with np.unravel_index():

import numpy as np

scores = np.array([[72, 88, 95],     # student 0
                   [91, 67, 80],     # student 1
                   [85, 99, 70]])    # student 2

print("overall max:", scores.max())
print("max per column (subject):", scores.max(axis=0))
print("max per row (student):   ", scores.max(axis=1))

flat = scores.argmax()                                   # index in the flattened array
row, col = np.unravel_index(flat, scores.shape)
print("argmax:", flat, "-> row, col:", (int(row), int(col)))

Output:

overall max: 99
max per column (subject): [91 99 95]
max per row (student):    [95 91 99]
argmax: 7 -> row, col: (2, 1)
Command Prompt output of NumPy max with axis 0 and axis 1 on a 2D score array and argmax converted to row and column with unravel_index
Per-column and per-row maxima, and the row/column of the overall maximum.

Arrays with NaN values

A single NaN makes max() return nan. Use the NaN-aware versions:

import numpy as np

readings = np.array([3.2, np.nan, 7.9, 5.1])

print("max:", readings.max())                 # NaN wins: result is nan
print("nanmax:", np.nanmax(readings))          # ignores NaN
print("nanargmax:", np.nanargmax(readings))

Output:

max: nan
nanmax: 7.9
nanargmax: 2

Empty arrays: ValueError

import numpy as np

try:
    max([])
except ValueError as e:
    print("max([]):", e)

print("with default:", max([], default=None))       # built-in max() can return a default

try:
    np.array([]).max()
except ValueError as e:
    print("np.array([]).max():", e)

Output:

max([]): max() iterable argument is empty
with default: None
np.array([]).max(): zero-size array to reduction operation maximum which has no identity
Command Prompt output of ValueError max() iterable argument is empty and zero-size array to reduction operation maximum which has no identity
Both errors, and the default= argument of the built-in max().

Maximum by a key, the longest string and the top values

products = [{"name": "Laptop", "price": 999}, {"name": "Phone", "price": 699},
            {"name": "Monitor", "price": 249}]

most_expensive = max(products, key=lambda p: p["price"])     # max by a field
print(most_expensive)

words = ["kiwi", "banana", "fig"]
print(max(words))            # alphabetical: the "largest" string
print(max(words, key=len))   # the longest word

import heapq
print(heapq.nlargest(2, [310, 450, 290, 450, 380]))   # the top 2 values

Output:

{'name': 'Laptop', 'price': 999}
kiwi
banana
[450, 450]

Which is faster: max() or NumPy?

import time
import numpy as np

values = np.random.default_rng(1).random(5_000_000)
as_list = values.tolist()

t = time.perf_counter(); m1 = max(as_list); t_list = time.perf_counter() - t
t = time.perf_counter(); m2 = values.max(); t_np = time.perf_counter() - t

print(f"built-in max on a list : {m1:.6f} in {t_list * 1000:6.1f} ms")
print(f"NumPy max on an array  : {m2:.6f} in {t_np * 1000:6.1f} ms")

Output (one run; timings vary):

built-in max on a list : 1.000000 in   41.1 ms
NumPy max on an array  : 1.000000 in    2.4 ms
Command Prompt timing comparison of Python built-in max on a list of five million numbers and NumPy max on an array
NumPy scans the array in compiled code; the built-in max() handles one Python object at a time.

If your data is already a NumPy array, use its methods; converting a list to an array just to find the maximum once is usually not worth it.

Related Python array tutorials:

Frequently asked questions

How do I find the maximum value in an array in Python?

Use max(values) for a list or arr.max() (or np.max(arr)) for a NumPy array.

How do I find the index of the maximum value?

values.index(max(values)) for a list, or np.argmax(arr) for NumPy. Both return the first index if the maximum appears more than once.

How do I get all indices of the maximum value?

np.flatnonzero(arr == arr.max()), or [i for i, v in enumerate(lst) if v == max(lst)].

How do I find the maximum of each row or column in NumPy?

arr.max(axis=1) for rows and arr.max(axis=0) for columns.

Why does np.max return nan?

The array contains NaN. Use np.nanmax() and np.nanargmax() to ignore missing values.

How do I avoid ValueError on an empty list?

Pass a default: max(values, default=None), or check if values: first.