Python Longest String in NumPy Array
To find the longest string in a given NumPy array, say arr
, you can use the max(arr, key=len)
function that determines the maximum by comparing the length of the array elements using the len()
function as a key for comparison.
import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) print(max(arr, key=len)) # Alice
You can find more about the powerful max()
function in our detailed blog tutorial:
π Recommended Tutorial: Python Maximum Function
Python Length of Longest String in NumPy Array
To find the length of the longest string in a NumPy array arr
, use the max(arr, key=len)
function to obtain the string with the maximum length and then pass this max string into the len()
function to obtain the number of characters of the max string.
len(max(arr, key=len))
Here’s a more detailed code example of a simple 1D NumPy Array:
import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) # Print Longest String: print(max(arr, key=len)) # Alice # Print Length of Longest String print(len(max(arr, key=len))) # 5
Get Longest String from NumPy Axis (2D, Column or Row)
To get the longest string from a certain NumPy array axis (e.g., row or column), first use simple NumPy slicing and indexing to get that axis (e.g., arr[0, :]
to get the first row) and pass it into the max()
function with the key
argument set to the length function like so: max(arr[0, :], key=len)
.
Here’s an example to get the longest string of the first row of a 2D array:
import numpy as np arr = np.array([['Alice', 'Bob', 'Carl'], ['Ann', 'Zoe', 'Leonard']]) print(max(arr[0, :], key=len)) # Alice
Here’s an example to get the longest string of the third column of a 2D array:
print(max(arr[:, 2], key=len)) # Leonard
You get the idea. π
If you want to get the longest string from the whole NumPy array, not only from a column or row or axis, first flatten it and then pass the flattened array into the max()
function using the key=len
argument.
π Recommended Tutorial: How to Flatten a NumPy Array?
Also, check out our tutorial on finding the shortest string in a NumPy array.