0

I have an array in numpy: [0 1 2 3]

When I try to get the first element with a[0], it throws: IndexError: too many indices for array

If I use for x in a: print(x) Python throws TypeError: iteration over a 0-d array

Attempting to make a list with list(a) throws TypeError: 'numpy.uint8' object is not iterable

How do I convert this list of numbers into a standard list?

2
  • Can you show how you created a? Commented Mar 28, 2019 at 3:49
  • It might help to see the dtype. And just to be sure type and shape. The errors are not consistent with the initial display. Also try repr(arr). Commented Mar 28, 2019 at 4:51

2 Answers 2

3

It would help to know how you created a so that we could try to reproduce the errors.

import numpy as np

a = np.array([0, 1, 2, 3])
print(a[0]) # 0

for x in a:
    print(x) # 0 1 2 3

# you can call list() to convert to a python list
print(list(a))

# you can also call the built-in numpy array method
print(a.tolist())

a = np.array(a)
print(a, type(a)) # [0 1 2 3] <class 'numpy.ndarray'>
print(a[0]) # 0
print(a[1]) # 1

All of these operations succeed. Python 3.7.1, Numpy 1.15.4

Sign up to request clarification or add additional context in comments.

Comments

1

Try to check the type of the array, using a=array('[0 1 2 3]', dtype='<U9') I was able to replicate the firts two errors. If that is the case try the following

b=list(str(a))
newArray=[]
for val in b:
    try:
        newArray.append(int(val))
    except ValueError:
        pass

Python will not change automatically the value of a string to int or floatas some others languajes. Hope it helps

1 Comment

Yes, the third error isn't consistent with the others. list(a) is essentially [x for x in a], so should produce the same error, not one referencing a 'uint8' object.

Your Answer

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