How to Fix Typeerror: ‘int’ object is not subscriptable

Posted by Marta on February 2, 2023 Viewed 13453 times

Card image cap

In this article, I will explain the main reason why you will encounter the Typeerror: ‘int’ object is not subscriptable error and a few different ways to fix it. I think it is essential to understand why this error occurs since a good understanding will help you avoid it in the future. And as consequence you will write better more reliable code.

This tutorial contains some code examples and possible ways to fix the error.

Typeerror: ‘int’ object is not subscriptable

The TypeError exception indicates that the operation executed is not supported or not meant to be. You will usually get this error when you pass to a function, arguments of the wrong type. In this case, I called a method that is not implemented by the class you are using.

The following code is the simplest case where you will encounter this error.

var_integer = 1
var_list = [3,5]

print(var_list[0])  
print(var_integer[0])

Output:

Traceback (most recent call last):
  File line 5, in <module>
    print(var_integer[0])
TypeError: 'int' object is not subscriptable

The error will occur at line 5 because I am trying to access item #0 of a collection; however, the variable is an integer number. When I try to access the item of a collection, behind the scene, python will call an internal method called__getitem__ . The integer type doesn’t implement this method since the integer type is a scalar(a plain number).

‘float’ object is not subscriptable

The float type is also a scalar type; therefore, using any container type of operation, like accessing an item, will return this error.

Here is an example. The following code will throw the typerror at line 5

var_float = 1.0
var_list = [3,5]

print(var_list[0])  
print(var_float[0]) # Error

Output:

Traceback (most recent call last):
File line 11, in <module>
	print(var_float[0]) 
TypeError: 'float' object is not subscriptable

You can avoid this error just by removing the square brackets at line 5

print(var_float)

Case 1: Example

Let’s see another code example where this Typeerror ‘int’ object is not subscriptable error occurs. Say that I want to write a program to calculate my lucky number based on my birth date. I will calculate my lucky number by adding all digits of my date of birth, in format dd/mm/yyyy, and then adding up the digits of the total. Here is an example:

Date of birth: 04/08/1984
4+8+1+9+8+4=34
3+4=7
Lucky number is 7

Here is the code I initially wrote to do this calculation:

birthday = '04/08/1984'

sum_month_digits = (int(birthday[0])+int(birthday[1]))
sum_day_digits = (int(birthday[3])+int(birthday[4]))
sum_year_digits= (int(birthday[6])+int(birthday[7])+int(birthday[8])+int(birthday[9]))

sum_all = sum_month_digits + sum_day_digits + sum_year_digits
lucky_number= (int(sum_all[0])+int(sum_all[1]))

print("Lucky number is", lucky_number)

Output:

Traceback (most recent call last):
File line 8, in <module>
	lucky_number= (int(sum_all[0])+int(sum_all[1]))
TypeError: 'int' object is not subscriptable

The error occurs at line #8. The reason is that the variable sum_all is an integer, not a string. Therefore I can’t treat this variable as a container and try to access each individual number. To fix this error, I could convert the sum_all variable to a string and then use the square brackets to access the digits.

lucky_number= (int(str(sum_all)[0])+int(str(sum_all)[1]))

The String type is a container like type, meaning that you can access each character using the index access. See the below example:

var_string='Hello'
print(var_string[0])

Output:

H

Case 2: Typeerror: ‘int’ object is not subscriptable json

Let’s see another scenario where this type error could arise. This error can also occur when you are working with JSON. As in the previous example, you will encounter the error when you treat a scalar variable, int or float, as a container and try to access by index.

Here is an example. The code below creates a product_json variable that contains a JSON with some products and information such as product name, category ,and product stock available. I would like to calculate the total stock available for all products.

import json
products_json='''
    {"products":
        [{"product":
            {"name":"Bike",
             "category":"sports",
             "stock": 4}
        },
        {"product":
            {"name":"Lamp",
             "category":"home",
             "stock": "3"}
        },
        {"product":
            {"name":"Table",
             "category":"home",
             "stock": "1"}
        }]
    }'''
products = json.loads(products_json)
products= products['products']
stock_list = [int(product['product']['stock'][0]) for product in products]
print(sum(stock_list))

Output:

Traceback (most recent call last):
  File line 22, in <listcomp>
    stock_list = [int(product['product']['stock'][0]) for product in products]
TypeError: 'int' object is not subscriptable

What is this code doing? The code will first parse the JSON text, capture the stock number for each product, and add up these numbers to get the total stock.

Why does the error occur? This error is in line 22. In this line, I am grabbing each stock, expected it to be a string, grab the first digit, and then convert it to an integer. Where is the problem? Double-checking the stock field carefully, you will see that the stock field is a number type for the first product but string for the rest.

     "stock": 4}  # Issue is here
   	 "stock": "3"}
     "stock": "1"}

Solution

The best way to solve this problem is to change the stock field for all products, so they are all numbers. I can do that just by removing the double-quotes. And next removing the ‘access by index’ at line 22. I can’t use access by index because the stock field is now an int. Let’s see how the code looks like after fixing it:

import json
products_json='''
    {"products":
        [{"product":
            {"name":"Bike",
             "department":"sports",
             "stock": 4}
        },
        {"product":
            {"name":"Lamp",
             "department":"home",
             "stock": 3} #Removed double quotes
        },
        {"product":
            {"name":"Table",
             "department":"home",
             "stock": 1} #Removed double quotes
        }]
    }'''
products = json.loads(products_json)
products= products['products']
stock_list = [int(product['product']['stock']) for product in products] #Removed access by index
print(sum(stock_list))

The above is just a simple example, but I think It helps get a better understanding of this error. The better you understand these errors, the easier it is for you to avoid them when you are programming.

Conclusion

To summarise, when you encounter this error is important to double-check all access by index operation, the square bracket, and make sure you are just using them against container variables, such as lists, strings, tuples, etc. I hope this helps, and thanks for reading and supporting this blog. Happy Coding!

Recommended articles

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java