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]
np.flatnonzero returns all of them.| Method | Returns | Notes |
|---|---|---|
lst.index(max(lst)) | First index | Simple; scans the list twice |
max(range(len(lst)), key=lst.__getitem__) | First index | One pass |
max(enumerate(lst), key=...) | (index, value) | Both at once |
np.argmax(arr) | First index | Fastest for large data |
np.flatnonzero(arr == arr.max()) | All indices | Handles 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)
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
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
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:
- 2D arrays in Python: lists and NumPy
- Check if a NumPy array is empty
- Sort a list of tuples by the second element
- Sort a dictionary in Python
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.
Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn