Blog |

How to Fix “Function Object is Not Subscriptable” in Python

How to Fix “Function Object is Not Subscriptable” in Python
Table of Contents

“Subscriptable” is just a fancy way of saying "something you can use square brackets on to get parts from it.” For example, my_list[0] and my_dict['key'] accesses the element at 0 and key, respectively.

In Python you can only use square brackets [] to access elements of a list, array, or dictionary. If you try to do the same thing with a function, you get the “function object is not subscriptable” error.

Simply put, you're trying to treat a function like it's a list, but you can't do that because they are different things.

“Function Object is Not Subscriptable” Example

Functions are objects. When you define a function, you create an object. For example:

def my_function():
    return [1, 2, 3]

You mistakenly treat a function like it's subscriptable when you use square brackets on it.

first_element = my_function[0]
Traceback (most recent call last):
  File "example.py", line X, in <module>
    result = my_function[0]
TypeError: 'function' object is not subscriptable

That raises the error because you’re trying to access the first element of a function, which isn’t possible.

How to Fix “Function Object is Not Subscriptable”

Continuing with the example above, if you want to return the first element in the function’s return value, you would need to call my_function() first and then access the first element of its return value, like this:

first_element = my_function()[0]

1

See the difference? When you try my_function[0], you’re using square brackets on the function itself, which doesn't make sense because a function isn't a list or array; it doesn't contain indexed elements.

Instead, you first need to call the function to get its return value, and then you can index that value since it's an array.

You should also review the function. Is it even returning a subscriptable object?

If you’re still not sure why this error is occurring, you can add print statements to check the types of your variables and make sure they are what you expect.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Install the Python SDK to identify and fix exceptions today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape