If you don't mind the function returning an array even if it is supplied with a scalar, I'd be inclined to do it this way:
import numpy as np
def foo(a,k=5):
b = np.array(a)
if not b.ndim:
b = np.array([a])
b[b < k] = 0
return b
print(foo(3))
print(foo(6))
print(foo([1,2,3,4,5,6,7,8,9]))
print(foo(np.array([1,2,3,4,5,6,7,8,9])))
... which produces the results:
[0]
[6]
[0 0 0 0 5 6 7 8 9]
[0 0 0 0 5 6 7 8 9]
As you can see from the test examples, this function works as intended if it is supplied with a regular Python list instead of a numpy array or a scalar.
Creating two arrays in the process may seem wasteful but, first, creating b prevents the function from having unwanted side-effects. Consider that:
def foobad(a,k=5):
a[a < k] = 0
return a
x = np.array([1,2,3,4,5,6,7,8,9])
foobad(x)
print (x)
... prints:
[0 0 0 0 5 6 7 8 9]
... which is probably not what was desired by the user of the function. Second, if the second array creation occurs because the function was supplied with a scalar, it will only be creating an array from a 1-element list, which should be very quick.
a.ndim == 0to recognize 0d-array. Take a look at this question stackoverflow.com/questions/773030/…zero_d_array[()]orzero_d_array[...]both work. There does seem to be a weird edge case with boolean advanced indexing, though.ain place? That'll produce strange inconsistencies between the scalar and array cases.