Python Shortest String in NumPy Array
To find the shortest string in a given NumPy array, say
arr, you can use the
min(arr, key=len) function that determines the minimum 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(min(arr, key=len)) # Bob
You can find more about the powerful
min() function in our detailed blog tutorial:
👉 Recommended Tutorial: Python Minimum Function
Python Length of Shortest String in NumPy Array
To find the length of the shortest string in a NumPy array
arr, use the
min(arr, key=len) function to obtain the string with the minimum length and then pass this min string into the
len() function to obtain the number of characters.
Here’s a more detailed code example of a simple 1D NumPy Array:
import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) # Print Shortest String: print(min(arr, key=len)) # Bob # Print Length of Shortest String print(len(min(arr, key=len))) # 3
Get Shortest String from NumPy Axis (2D, Column or Row)
To get the shortest 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
min() function with the
key argument set to the length function like so:
min(arr[0, :], key=len).
Here’s an example to get the shortest string of the first row of a 2D array:
import numpy as np arr = np.array([['Alice', 'Bob', 'Carl'], ['Ann', 'Zoe', 'Leonard']]) print(min(arr[0, :], key=len)) # Bob
Here’s an example to get the shortest string of the third column of a 2D array:
print(min(arr[:, 2], key=len)) # Carl
You get the idea. 🙂
If you want to get the shortest 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
min() function using the
👉 Recommended Tutorial: How to Flatten a NumPy Array?
Also, check out our tutorial on finding the maximum 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. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, 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.