Solution for the “TypeError: ‘numpy.ndarray’ object is not callable” error in Python

If you struggle to fix the ” TypeError: ‘numpy.ndarray’ object is not callable” error in Python, this article will give you all the necessary information. This error occurs when we call a NumPy array like a function. You must use the square brackets instead of the parentheses to fix it. Keep reading for detailed information. 

Why does this error occur?

You will receive the error message: “TypeError: ‘numpy.ndarray’ object is not callable” in Python when we try to apply a function call to a NumPy array.

Here is an example of how this error occurs:

import numpy as np

newArr = np.array([0, 2, 4, 6, 8])

# Use the parentheses with the NumPy array
for i in range(len(newArr)):
    print(newArr(i))

Error:

TypeError: 'numpy.ndarray' object is not callable

Moreover, errors will likely occur in your program when you have the same function name and variable name. For example:

import numpy as np

# Declare a function named 'evenNumber'
def evenNumber(n):
    if n % 2 == 0:
        return True
    return False

# Declare a NumPy array named 'evenNumber'
evenNumber = np.array([0, 2, 4, 6, 8])
print(evenNumber(9))

Error:

TypeError: 'numpy.ndarray' object is not callable

The ‘evenNumber’ function is now shadowed by the ‘evenNumber’ array, so we cannot use the statement ‘evenNumber(8)’.

Solved – TypeError: ‘numpy.ndarray’ object is not callable in Python

To work around this problem, make sure to use the square brackets instead of the parentheses when accessing the element in the NumPy array.

import numpy as np

newArr = np.array([0, 2, 4, 6, 8])

# Access the element using square brackets
for i in range(len(newArr)):
    print(newArr[i])

Output:

0
2
4
6
8

In case you have a function and a variable with the same name, rename them to different values ​​so that the error no longer occurs.

import numpy as np

# Declare a function named 'evenNumber'
def evenNumber(n):
    if n % 2 == 0:
        return True
    return False

# Rename the NumPy array from 'evenNumber' to 'evenNumberArr'
evenNumberArr = np.array([0, 2, 4, 6, 8])
print(evenNumber(9))

Output:

False

Summary

In summary, we have shown you the cause of the “TypeError: ‘numpy.ndarray’ object is not callable” error in Python and its solution. Make sure to use the square brackets instead of the parentheses when accessing the element in the NumPy array, and don’t have a function and a variable with the same name in your code. Hopefully, the information we provided in this article will be helpful to you.

Leave a Reply

Your email address will not be published. Required fields are marked *