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.
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
👉 Recommended Tutorial: How to Flatten a NumPy Array?
Also, check out our tutorial on finding the shortest string in a NumPy array.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.