1

Somehow I do not understand the error message I am getting:

IndexError: too many indices for array

I have looked into other questions with that title but none seem to apply to my situation. This is my code.

import numpy as np


def revert_array(array):
    max_len = len(array)
    ret = np.array(max_len)
    for i in range(1, max_len):
        ret[i] = array[max_len - i]
    return ret


a = np.array([1,2,3,4])
r = revert_array(a)

print(r)

I do give only an integer value as the index. What am I missing?

1
  • 1
    this line ret = np.array(max_len) causes error. However, I am not sure about logic of your function, so I can't tell how to fix it. Commented Oct 9, 2020 at 8:47

2 Answers 2

2

The statement

ret = np.array(max_len)

is not returning the desired empty array, because of that you are getting this error

This should work

import numpy as np


def revert_array(array):
    max_len = len(array)
    ret = np.zeros(max_len)
    for i in range(1, max_len):
        ret[i] = array[max_len - i]
    return ret


a = np.array([1,2,3,4])
r = revert_array(a)

print(r)

Output

[0. 4. 3. 2.]

Another way to create empty array in numpy

ret = np.empty(shape=(max_len))

Here you are trying to reverse the input array, but above logic has some problems, below code should reverse the array

import numpy as np


def revert_array(array):
    max_len = len(array)
    ret = np.zeros(max_len)
    for i in range(0, max_len):
        ret[i] = array[max_len - 1 - i]
    return ret


a = np.array([1,2,3,4])
r = revert_array(a)

print(r)

Output

[4. 3. 2. 1.]
Sign up to request clarification or add additional context in comments.

Comments

1

First of all, as anuragal answers, if you pass an integer to np.array, an array of that length is not created. For that, you have to use something like np.zeros or np.empty and pass in an array shape (which in your case, is simply one integer, so a 1-D array will be created). Always read the docs to understand how functions work.

Secondly, since it seems like you are trying to reverse an array, (the hard way, using loops!) numpy arrays start with the index 0: so you need to run that loop starting at zero.

Thirdly, if reversing this way is not purely out of academic interest, array[::-1] does the job. How does it work? Read this document on indexing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.