Question Details

No question body available.

Tags

python numpy

Answers (2)

Accepted Answer Available
Accepted Answer
April 3, 2026 Score: 4 Rep: 45,763 Quality: Expert Completeness: 80%

The function is called twice to determine the number of outputs.

numpy.vectorize documentation (Notes):

If neither otypes nor signature are specified, then a call to the function with the first argument will be used to determine the number of outputs. The results of this call will be cached if cache is True to prevent calling the function twice. However, to implement the cache, the original function must be wrapped which will slow down subsequent calls, so only do this if your function is expensive.


Specifying the type will prevent the second call:

print(np.vectorize(f, otypes=[object])(["input"]))

Setting cache to True:

print(np.vectorize(f, cache=True)(["input"]))

Those both output

hi input
['input']

You can also specify the signature:

print(np.vectorize(f, signature="(m)->(m)")(["input"]))

This will output

hi ['input']
['input']

Try it online!

April 3, 2026 Score: 4 Rep: 46,349 Quality: Medium Completeness: 70%

If you look at the documentation for numpy.vectorize, you will see:

The data type of the output of vectorized is determined by calling the function with the first element of the input. This can be avoided by specifying the otypes argument.

So, function f is called once just to determine the types being returned. Try:

print(np.vectorize(f, [str])(["input"]))