# IndexError when using Enumerated Indexes in NumPy

## Question:

I am trying to create a fifth-order FIR filter in Python described by the following difference equation (apologies dark mode users but LaTeX is not yet supported on SO):

$y(n) = \sum_{k=0}^{5}h(k)x(n-k)$

``````def filter(x):

h = np.array([-0.0147, 0.173, 0.342, 0.342, 0.173, -0.0147])
y = np.zeros_like(x)

buf_array = np.zeros_like(h)
buf = 0.0

for n in enumerate(x):
for k in enumerate(h):
buf = h[k]*x[n-k]
buf_array[k] = buf

y[n] = np.sum(buf_array)

return y
``````

When using the filter, the Traceback leads me to the following line:

``````     10 for n in enumerate(x):
11     for k in enumerate(h):
---> 12         buf = h[k]*x[n-k]
13         buf_array[k] = buf
15     y[n] = np.sum(buf_array)

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
``````

I have tried playing around with indexes and all, but have not managed to understand why this error is being caused.

TIA

As someone suggested in the comments, this case use requires looping over indexes and elements on their own, as using `for index in enumerate(ndarray)` will result in `index` being a tuple rather than being an integer. Furthermore, using `for index, item in enumerate(ndarray)` is suggested, as shown below:

``````# Filter function
def filter(x):

h = np.array([-0.0147, 0.173, 0.342, 0.342, 0.173, -0.0147])
y = np.zeros_like(x)

buf_array = np.zeros_like(h)
buf = 0.0

for n, n_i in enumerate(x):
for k, k_i in enumerate(h):
i = n-k
buf = h[k]*x[i]
buf_array[k] = buf

y[n] = np.sum(buf_array)

return y
``````
Categories: questions
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.