Suppose I have this:
def incrementElements(x):
return x+1
but I want to modify it so that it can take either a numpy array, an iterable, or
This is an old question, but here are my two cents.
Although Pierre GM's answer works great, it has the---maybe undesirable---side effect of converting scalars to arrays. If that is what you want/need, then stop reading; otherwise, carry on. While this might be okay (and is probably good for lists
and other iterables
to return a np.array
), it could be argued that for scalars it should return a scalar. If that's the desired behaviour, why not follow python's EAFP philosophy. This is what I usually do (I changed the example to show what could happen when np.asarray
returns a "scalar"):
def saturateElements(x):
x = np.asarray(x)
try:
x[x>1] = 1
except TypeError:
x = min(x,1)
return x
I realize it is more verbose than Pierre GM's answer, but as I said, this solution will return a scalar if a scalar is passed, or a np.array
is an array or iterable is passed.