One common error you may encounter when using NumPy in Python is:
TypeError: 'numpy.ndarray' object is not callable
This error usually occurs when you attempt to call a NumPy array as a function by using round () brackets instead of square [ ] brackets.
The following example shows how to use this syntax in practice.
How to Reproduce the Error
Suppose we have the following NumPy array:
import numpy as np #create NumPy array x = np.array([2, 4, 4, 5, 9, 12, 14, 17, 18, 20, 22, 25])
Now suppose we attempt to access the first element in the array:
#attempt to access the first element in the array
x(0)
TypeError: 'numpy.ndarray' object is not callable
Since we used round () brackets Python thinks we’re attempting to call the NumPy array x as a function.
Since x is not a function, we receive an error.
How to Fix the Error
The way to resolve this error is to simply use square [ ] brackets when accessing elements of the NumPy array instead of round () brackets:
#access the first element in the array
x[0]
2
The first element in the array (2) is shown and we don’t receive any error because we used square [ ] brackets.
Also note that we can access multiple elements of the array at once as long as we use square [ ] brackets:
#find sum of first three elements in array
x[0] + x[1] + x[2]
10
Additional Resources
The following tutorials explain how to fix other common errors in Python:
How to Fix: ValueError: Index contains duplicate entries, cannot reshape
How to Fix: Typeerror: expected string or bytes-like object
How to Fix: TypeError: ‘numpy.float64’ object is not callable