15.1 C
London
Friday, July 5, 2024
HomePythonFix Common Errors in PythonHow to Fix in Python: ‘numpy.ndarray’ object is not callable

How to Fix in Python: ‘numpy.ndarray’ object is not callable

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories