Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm using a numpy object_ array to store variable length strings, e.g.

a = np.array(['hello','world','!'],dtype=np.object_)

Is there an easy way to find the length of the longest string in the array without looping over all elements?

share|improve this question
add comment

3 Answers

up vote 1 down vote accepted

max(a, key=len) gives you the longest string (and len(max(a, key=len)) gives you its length) without requiring you to code an explicit loop, but of course max will do its own looping internally, as it couldn't possibly identify "the longest string" in any other way.

share|improve this answer
add comment

No as the only place the length of each string is known is by the string. So you have to find out from every string what its length is.

share|improve this answer
add comment

If you store the string in a numpy array of dtype object, then you can't get at the size of the objects (strings) without looping. However, if you let np.array decide the dtype, then you can find out the length of the longest string by peeking at the dtype:

In [64]: a = np.array(['hello','world','!','Oooh gaaah booo gaah?'])

In [65]: a.dtype
Out[65]: dtype('|S21')

In [72]: a.dtype.itemsize
Out[72]: 21
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.