TypeError: Iteration Over a 0-D Array in Python

TypeError: Iteration Over a 0-D Array in Python

  1. Numpy Arrays and Their Dimension
  2. the TypeError: iteration over a 0-d array in Python
  3. Fix the TypeError: iteration over a 0-d array in Python

Python’s Numpy library works with arrays and performs Mathematical operations. Numpy arrays require a list of data to convert the information into a ndarray.

If we pass anything else, e.g., an iterator, they will result in an error named TypeError: iteration over a 0-d array.

Numpy Arrays and Their Dimension

Numpy’s primary object is ndarray, an array object. It uses a typical Python array or list to create the ndarray.

The ndarray can now utilize all the functions available in Numpy.

Numpy can have arrays of different dimensions. We can check the dimension of ndarray using the ndim attribute.

Example Code:

#Python 3.x
import numpy as np
array = np.array(3)
array1 = np.array([3,1])
array2 = np.array([[1,3],[4,2]])
print(array.ndim)
print(array1.ndim)
print(array2.ndim)

Output:

#Python 3.x
0
1
2

the TypeError: iteration over a 0-d array in Python

It will give the error if we pass an iterator instead of a list. Because Numpy arrays need an array to make their ndarray, an iterator would not work correctly here.

Example Code:

#Python 3.x
import numpy as np
dictionary = {}
keys,values = np.array(dictionary.items())

Output:

#Python 3.x
TypeError: iteration over a 0-d array

Fix the TypeError: iteration over a 0-d array in Python

We can convert the iterator into a list when supplying it to the np.array() function. Getting a list as a parameter would make the function work correctly.

In the following code, we have created a dictionary. To make a ndarray using this dict, first, we have to convert the dictionary to a list and pass it as an argument to nd.array().

Example Code:

#Python 3.x
import numpy as np
data = {
    "Jhon": 90,
    "Alia": 80,
    "Jack": 70,
}
keys, values = np.array(list(data.items())).T
print(keys)
print(values)

Output:

#Python 3.x
['Jhon' 'Alia' 'Jack']
['90' '80' '70']
Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

LinkedIn

Related Article - Python Error

  • Local Variable Referenced Before Assignment Error in Python
  • Python Handling Socket.Error: [Errno 104] Connection Reset by Peer
  • Python Is Not Recognized in Windows 10
  • NameError: The OS Module Is Not Defined in Python
  • Python ValueError: Not Enough Values to Unpack
  • Resolve the TypeError: Can't Multiply Sequence by Non-Int of Type STR in Python