Open In App

Find the Length of Each String Element in the Numpy Array

Last Updated : 27 Sep, 2025
Suggest changes
Share
Like Article
Like
Report

When working with string arrays in NumPy, we often need to calculate length of each string element. Instead of looping manually, NumPy and Python provide multiple efficient ways to achieve this.

Let’s see different methods to find the length of each string in a NumPy array.

Using numpy.char.str_len()

The function np.char.str_len() directly computes the length of each string element in the array and returns a new array of integers. This is the most efficient and NumPy-recommended method.

Example: In this example, we find string lengths using np.char.str_len().

Python
import numpy as np
arr = np.array(['New York', 'Lisbon', 'Beijing', 'Quebec'])
res = np.char.str_len(arr)
print(res)

Output
[8 6 7 6]

Explanation: Here, np.char.str_len() calculates the number of characters in each string efficiently and returns a NumPy array with lengths.

Using numpy.vectorize() with len

The np.vectorize() function turns a Python function (like len) into a vectorized version that works element-wise on NumPy arrays. It is convenient but slower than np.char.str_len() because it still calls Python functions internally.

Example: In this example, we apply len to each string using np.vectorize().

Python
import numpy as np
arr = np.array(['Paris', 'London', 'Delhi', 'Tokyo'])
le = np.vectorize(len)(arr)
print(le)

Output
[5 6 5 5]

Explanation: Here, np.vectorize(len) applies len() to every element in the array and returns their lengths as a NumPy array.

Using List Comprehension

List comprehension provides a simple and Pythonic way to calculate string lengths. Although it is not as fast as NumPy methods, it is easy to understand and works well for smaller arrays.

Example: In this example, we compute lengths using list comprehension.

Python
import numpy as np
arr = np.array(['Apple', 'Banana', 'Mango', 'Kiwi'])
res = [len(s) for s in arr]
print(res)

Output
[5, 6, 5, 4]

Explanation: Here, len(s) is applied to each string in the array using Python’s list comprehension, producing a list of string lengths.


Explore