All the power and beauty of Numpy in vectorized ufuncs (optimized functions written in C / Cython and therefore very fast). In general, Numpy has vectorize () for functions that work with scalars and apply_along_axis () for functions that work with lists, BUT it’s the same for ... cycle and in speed it is unlikely to be faster. Knowing a specific problem, we could try to find a vectorized (fast) solution ...
Example:
In [130]: a = np.random.randint(10**4, size=(10**6)) In [131]: import math In [132]: def f(lst): ...: return [math.sin(x) * math.cos(x) for x in lst] ...: In [133]: a.shape Out[133]: (1000000,) In [134]: %timeit f(a[1::2]) 866 ms ± 886 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) In [135]: %timeit np.apply_along_axis(f, 0, a[1::2]) 932 ms ± 183 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
If your function works with scalars :
In [137]: def f(x): ...: return math.sin(x) * math.cos(x) ...: In [138]: vfunc = np.vectorize(f) In [139]: %timeit vfunc(a[1::2]) 969 ms ± 19.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Vector solution:
In [136]: %timeit np.sin(a[1::2]) * np.cos(a[1::2]) 65.4 ms ± 92.7 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Conclusion: you must first try to find a vectorized solution. If this is not possible, then other options should be compared and, perhaps, " list comprehension " will be faster (as in my example) ...
for ...cycle and in speed it is unlikely to be faster. Knowing a specific problem, we could try to find a vectorized (fast) solution ... - MaxU