TypeError: 'numpy.ndarray' object is not callable in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

TypeError: 'numpy.ndarray' object is not callable in Python #

The Python "TypeError: 'numpy.ndarray' object is not callable" occurs when we try to call an array as if it were a function. To solve the error, make sure to use square brackets when accessing an array element at a specific index, e.g. my_array[0].

typeerror numpy ndarray object is not callable

Here is one example of how the error occurs.

main.py
import numpy as np arr = np.array([1, 2, 3, 4]) # ⛔️ TypeError: 'numpy.ndarray' object is not callable print(arr(1)) # 👈️ using parenthesis

The issue in the code sample is that we used parenthesis instead of square brackets when accessing the array at a specific index.

main.py
import numpy as np arr = np.array([1, 2, 3, 4]) # ✅ now using square brackets to access index print(arr[0]) # 👉️ 1 print(arr[1]) # 👉️ 2 print(arr[2]) # 👉️ 3 print(arr[3]) # 👉️ 4

Make sure you don't have a function and a variable with the same name.

main.py
import numpy as np def example(): return 'hello world' example = np.array([1, 2, 3, 4]) # ⛔️ TypeError: 'numpy.ndarray' object is not callable example()

The example variable shadows the function with the same name, so when we try to call the function, we actually end up calling the variable.

Renaming the variable or the function solves the error.

Make sure you aren't trying to call an array as a function in your code.

main.py
import numpy as np arr = np.array([1, 2, 3, 4]) # ⛔️ TypeError: 'numpy.ndarray' object is not callable arr() # 👈️ remove parenthesis

The error also occurs if we override the classes and methods from the numpy module.

For example, don't import array from numpy and declare a variable named numpy as it would shadow the official class.

Use the search field on my Home Page to filter through my more than 1,000 articles.