Sling Academy
Home/Python/How to Fix Python TypeError: ‘int’ object is not subscriptable

How to Fix Python TypeError: ‘int’ object is not subscriptable

Last updated: January 02, 2024

Understanding the Error

Encountering a TypeError: ‘int’ object is not subscriptable in Python can be puzzling for developers, especially those new to the language. This error often happens when one mistakenly tries to access an index of an integer and treats it as an iterable like a list, string, or tuple.

Before delving into solutions, it’s important to understand what the error message means. A subscriptable object in Python is anything capable of being accessed via indices – meaning you can use square brackets to get an element, like my_list[0] for lists or my_string[1] for strings. An integer is a whole number and not an iterable object, so attempting to use an index operation on it, like my_int[0], will cause this error.

Solution Overview: Checking the Variable Type

In general, you can get through the error by following this process:

  1. Identify where the error is being thrown.
  2. Review the involved variables and check the data types.
  3. Correct the code to avoid using indexing on integers.

A code that demonstrates how to cause the mentioned error:

my_var = 42
try:
    # Incorrect indexing on an integer.
    print(my_var[0])
except TypeError as e:
    print(e)
    # Output correct value or implement other logic.
    print(my_var)

Solution 1: Debug and Modify Code

Here’s a step-by-step guide to inspecting the code and correcting the issue.

  1. Determine where in the code the error occurs.
  2. Understand the context and intended operation.
  3. Modify the code to remove indexing from the integer variable.

Example:

# Incorrect code
number = 5
print(number[0])   # This is wrong

# Corrected code
number = 5
print(number)      # This is correct

Some thoughts:

  • Advantages: Simple, no extra code necessary.
  • Limitations: Not applicable for complex data types or errors due to misplaced variables.

Solution 2: Confirm Variable Assignment

This approach ensures that the correct type of variable is being manipulated:

  1. Examine the variable assignments leading to the erroneous operation.
  2. Validate the integrity of the operations performed on the variable.
  3. Rewrite any incorrect assignments or operations.

Example:

# Possible cause of misassignment
numbers = {'a':1, 'b':2}
number = numbers    # A dictionary variable

# Mistakenly trying to index the dictionary as a whole
print(number[0])

# Instead, access the dictionary values correctly
key_lookup = 'a'
print(numbers[key_lookup])

Solution 3: Explicit Type Conversion

Converting data types to the expected iterable forms can solve the issue when a stringified integer is expected to act like a string:

  1. Locate the operation where the error is thrown.
  2. Determine if the variable type should be converted.
  3. Use cast functions like str() to convert the integer to a string if subscripting is intended.

Example:

# An integer cannot be subscripted
num = 1234

# Converting to a string allows subscripting
num_str = str(num)
print(num_str[0])

Some thoughts:

  • Advantages: Makes subscripting of number representations possible.
  • Limitations: Introduces a step of conversion which might not be always necessary or intended. It also changes the type of data being manipulated.

Next Article: Fixing AttributeError: ‘str’ object has no attribute ‘read’ in Python

Series: Common Errors in Python and How to Fix Them

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots