Int object is not subscriptable как исправить

The Python error "TypeError: 'int' object is not subscriptable" occurs when you try to treat an integer like a subscriptable object. In Python, a subscriptable object is one you can “subscript” or iterate over. Why the "TypeError: 'int' object is not subscriptable Error" Occurs You can iterate over a string, list, tuple, or even dictionary. But it is not possible to iterate over an integer or set of numbers. So, if you get this error, it means you’re trying to iterate over an integer or you’r

TypeError: 'int' object is not subscriptable [Solved Python Error]

The Python error «TypeError: ‘int’ object is not subscriptable» occurs when you try to treat an integer like a subscriptable object.

In Python, a subscriptable object is one you can “subscript” or iterate over.

You can iterate over a string, list, tuple, or even dictionary. But it is not possible to iterate over an integer or set of numbers.

So, if you get this error, it means you’re trying to iterate over an integer or you’re treating an integer as an array.

In the example below, I wrote the date of birth (dob variable) in the ddmmyy format. I tried to get the month of birth but it didn’t work. It threw the error “TypeError: ‘int’ object is not subscriptable”:

dob = 21031999
mob = dob[2:4]

print(mob)

# Output: Traceback (most recent call last):
#   File "int_not_subable..py", line 2, in <module>
#     mob = dob[2:4]
# TypeError: 'int' object is not subscriptable

How to Fix the «TypeError: ‘int’ object is not subscriptable» Error

To fix this error, you need to convert the integer to an iterable data type, for example, a string.

And if you’re getting the error because you converted something to an integer, then you need to change it back to what it was. For example, a string, tuple, list, and so on.

In the code that threw the error above, I was able to get it to work by converting the dob variable to a string:

dob = "21031999"
mob = dob[2:4]

print(mob)

# Output: 03

If you’re getting the error after converting something to an integer, it means you need to convert it back to string or leave it as it is.

In the example below, I wrote a Python program that prints the date of birth in the ddmmyy format. But it returns an error:

name = input("What is your name? ")
dob = int(input("What is your date of birth in the ddmmyy order? "))
dd = dob[0:2]
mm = dob[2:4]
yy = dob[4:]
print(f"Hi, {name}, nYour date of birth is {dd} nMonth of birth is {mm} nAnd year of birth is {yy}.")

#Output: What is your name? John Doe
# What is your date of birth in the ddmmyy order? 01011970
# Traceback (most recent call last):
#   File "int_not_subable.py", line 12, in <module>
#     dd = dob[0:2]
# TypeError: 'int' object is not subscriptable

Looking through the code, I remembered that input returns a string, so I don’t need to convert the result of the user’s date of birth input to an integer. That fixes the error:

name = input("What is your name? ")
dob = input("What is your date of birth in the ddmmyy order? ")
dd = dob[0:2]
mm = dob[2:4]
yy = dob[4:]
print(f"Hi, {name}, nYour date of birth is {dd} nMonth of birth is {mm} nAnd year of birth is {yy}.")

#Output: What is your name? John Doe
# What is your date of birth in the ddmmyy order? 01011970
# Hi, John Doe,
# Your date of birth is 01
# Month of birth is 01
# And year of birth is 1970.

Conclusion

In this article, you learned what causes the «TypeError: ‘int’ object is not subscriptable» error in Python and how to fix it.

If you are getting this error, it means you’re treating an integer as iterable data. Integers are not iterable, so you need to use a different data type or convert the integer to an iterable data type.

And if the error occurs because you’ve converted something to an integer, then you need to change it back to that iterable data type.

Thank you for reading.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Table of Contents
Hide
  1. What is Subscriptable in Python?
  2. How do you make an object Subscriptable?
  3. How to Fix TypeError: ‘int’ object is not subscriptable?
    1. Solution
  4. Conclusion

In Python, we use Integers to store the whole numbers, and it is not a subscriptable object. If you treat an integer like a subscriptable object, the Python interpreter will raise TypeError: ‘int’ object is not subscriptable.

In this tutorial, we will learn what ‘int’ object is is not subscriptable error means and how to resolve this TypeError in your program with examples.

Subscriptable” means that you’re trying to access an element of the object. The elements are usually accessed using indexing since it is the same as a mathematical notation that uses actual subscripts.

How do you make an object Subscriptable?

In Python, any objects that implement the __getitem__ method in the class definition are called subscriptable objects, and by using the  __getitem__  method, we can access the elements of the object.

For example, strings, lists, dictionaries, tuples are all subscriptable objects. We can retrieve the items from these objects using indexing.

Note: Python doesn't allow to subscript the NoneType if you do Python will raise TypeError: 'NoneType' object is not subscriptable

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

Let us take a small example to read the birth date from the user and slice the day, months and year values into separate lines.

birth_date = int(input("Please enter your birthdate in the format of (mmddyyyy) "))

birth_month = birth_date[0:2]
birth_day = birth_date[2:4]
birth_year = birth_date[4:8]

print("Birth Month:", birth_month)
print("Birth Day:", birth_day)
print("Birth Year:", birth_year)

If you look at the above program, we are reading the user birth date as an input parameter in the mmddyy format.

Then to retrieve the values of the day, month and year from the user input, we use slicing and store it into a variable.

When we run the code, Python will raise a TypeError: ‘int’ object is not subscriptable.

Please enter your birthdate in the format of (mmddyyyy) 01302004
Traceback (most recent call last):
  File "C:PersonalIJSCodemain.py", line 3, in <module>
    birth_month = birth_date[0:2]
TypeError: 'int' object is not subscriptable

Solution

 In our example, we are reading the birth date as input from the user and the value is converted to an integer. 

The integer values cannot be accessed using slicing or indexing, and if we do that, we get the TypeError. 

To solve this issue, we can remove the int() conversion while reading the input from the string. So now the birth_date will be of type string, and we can use slicing or indexing on the string variable.

Let’s correct our example and run the code.

birth_date = input("Please enter your birthdate in the format of (mmddyyyy) ")

birth_month = birth_date[0:2]
birth_day = birth_date[2:4]
birth_year = birth_date[4:8]

print("Birth Month:", birth_month)
print("Birth Day:", birth_day)
print("Birth Year:", birth_year)

Output

Please enter your birthdate in the format of (mmddyyyy) 01302004
Birth Month: 01
Birth Day: 30
Birth Year: 2004

The code runs successfully since the int() conversion is removed from the code, and slicing works perfectly on the string object to extract a day, month and year.

Conclusion

The TypeError: ‘int’ object is not subscriptable error occurs if we try to index or slice the integer as if it is a subscriptable object like list, dict, or string objects.

The issue can be resolved by removing any indexing or slicing to access the values of the integer object. If you still need to perform indexing or slicing on integer objects, you need to first convert that into strings or lists and then perform this operation.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

Introduction

Some of the objects in python are subscriptable. This means that they hold and hold other objects, but an integer is not a subscriptable object. We use Integers used to store whole number values in python. If we treat an integer as a subscriptable object, it will raise an error. So, we will be discussing the particular type of error that we get while writing the code in python, i.e., TypeError: ‘int’ object is not subscriptable. We will also discuss the various methods to overcome this error.

What is TypeError?

The TypeError occurs when you try to operate on a value that does not support that operation. Let us understand with the help of an example:

Suppose we try to concatenate a string and an integer using the ‘+’ operator. Here, we will see a TypeError because the + operation is not allowed between the two objects that are of different types.

#example of typeError

S = "Latracal Solutions"
number = 4
print(S + number)

Output:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    print(S + number)
TypeError: can only concatenate str (not "int") to str

Explanation:

Here, we have taken a string ‘Latracal Solutions” and taken a number. After that, in the print statement, we try to add them. As a result: TypeError occurred.

What is ‘int’ object is not subscriptable?

When we try to concatenate string and integer values, this message tells us that we treat an integer as a subscriptable object. An integer is not a subscriptable object. The objects that contain other objects or data types, like strings, lists, tuples, and dictionaries, are subscriptable. Let us take an example :

1. Number: typeerror: ‘int’ object is not subscriptable

#example of integer which shows a Typeerror

number = 1500
print(number[0])

output:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    print(number[0])
TypeError: 'int' object is not subscriptable

Explanation:

Here, we have taken a number and tried to print the through indexing, but it shows type error as integers are not subscriptable.

2. List: typeerror: ‘int’ object is not subscriptable

This TyperError problem doesn’t occur in the list as it is a subscriptable object. We can easily perform operations like slicing and indexing.

#list example which will run correctly

Names = ["Latracal" , " Solutions", "Python"]
print(Names[1])

Output:

Solutions

Explanation:

Here firstly, we have taken the list of names and accessed it with the help of indexing. So it shows the output as Solutions.

Daily Life Example of How typeerror: ‘int’ object is not subscriptable can Occur

Let us take an easy and daily life example of your date of birth, written in date, month, and year. We will write a program to take the user’s input and print out the date, month, and year separately.

#Our program begins from here

Date_of_birth = int(input("what is your birth date?"))

birth_date = Date_of_birth[0:2]

birth_month = Date_of_birth[2:4]

birth_year = Date_of_birth[4:8]

print(" birth_date:",birth_date)
print("birth_month:",birth_month)
print("birth_year:",birth_year)

Output:

what is your birth date?31082000
Traceback (most recent call last):
  File "C:/Users/lenovo/Desktop/fsgedg.py", line 3, in <module>
    birth_date = Date_of_birth[0:2] 
TypeError: 'int' object is not subscriptable

Explanation:

Here firstly, we have taken the program for printing the date of birth separately with the help of indexing. Secondly, we have taken the integer input of date of birth in the form of a date, month, and year. Thirdly, we have separated the date, month, and year through indexing, and after that, we print them separately, but we get the output ad TypeError: ‘int’ object is not subscriptable. As we studied above, the integer object is not subscriptable.

Solution of TypeError: ‘int’ object is not subscriptable

We will make the same program of printing data of birth by taking input from the user. In that program, we have converted the date of birth as an integer, so we could not perform operations like indexing and slicing.

To solve this problem now, we will remove the int() statement from our code and run the same code.

#remove int() from the input()

Date_of_birth = input("what is your birth date?")

birth_date = Date_of_birth[0:2]

birth_month = Date_of_birth[2:4]

birth_year = Date_of_birth[4:8]

print(" birth_date:",birth_date)
print("birth_month:",birth_month)
print("birth_year:",birth_year)

Output:

what is your birth date?31082000
 birth_date: 31
birth_month: 08
birth_year: 2000

Explanation:

Here, we have just taken the input into the string by just removing the int(), and now we can do indexing and slicing in it easily as it became a list that is subscriptable, so no error arises.

Must Read

Conclusion: Typeerror: ‘int’ object is not subscriptable

We have learned all key points about the TypeError: ‘int’ object is not subscriptable. There are objects like list, tuple, strings, and dictionaries which are subscriptable. This error occurs when you try to do indexing or slicing in an integer.

Suppose we need to perform operations like indexing and slicing on integers. Firstly, we have to convert the integer into a string, list, tuple, or dictionary.

Now you can easily the solve this python TypeError like an smart coder.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Table of Contents

  • ◈ Introduction
  • ➥ What Does Object Not Subscriptable Mean?
  • ➥ What is a TypeError In Python?
  • ➥ What is: TypeError:’int’ object is not subscriptable?
  • ✨ Scenario 1: Trying To Access Index Of An Integer Object
    • ✯ Method 1: Convert Integer Object to a String Object
    • ✯ Method 2: Overwrite the __getitem__ Method
  • ✨ Scenario 2: Treating an Integer as a List
  • Conclusion

◈ Introduction

In this article, we will be discussing certain type of error in Python. To be more specific we will be discussing the reason behind the occurrence of : TypeError: 'int' Object Is Not Subscriptable in Python and the methods to overcome such errors.

Let’s have a look at an example which demonstrates the occurrence of such errors.

Example: Consider the following program:

num = int(input(«Enter a 3 digit number? «))

sum_digit = num[0]+num[1]+num[2]

print(sum_digit)

Output:

Traceback (most recent call last):

  File «D:/PycharmProjects/pythonProject1/TypeError Not Subscriptable.py», line 7, in <module>

    sum_digit = num[0]+num[1]+num[2]

TypeError: ‘int’ object is not subscriptable

If you have come across a similar bug/error, then it must have been really frustrating! 😩

But it also brings us to a list of questions:

  • What does object not Subscriptable mean?
  • What is a TypeError?
  • What is TypeError:'int' object is not subscriptable ?
  • How do I fix: TypeError:'int' object is not subscriptable ?

Hence, without further delay let us discover the answers to our questions and then solve our problem.

➥ What Does Object Not Subscriptable Mean?

In simple terms, a subscriptable object in Python is an object that can contain other objects, i.e., the objects which are containers can be termed as subscriptable objects. Strings, tuples, lists and dictionaries are examples of subscriptable objects in Python.

Why is Integer not a subscriptable Object?

Integers are whole numbers. They cannot contain other objects within them. Further, subscriptable objects implement the __getitem__() method and integer objects do not implement the __getitem__() method.

TypeError is raised when a certain operation is applied to an object of an incorrect type. For example, if you try to add a string object and an integer object using the + operator, then you will encounter a TypeError because the + operation is not allowed between the two objects that are f different types.

Example:

Output:

TypeError: can only concatenate str (not «int») to str

➥ What is: TypeError:’int’ object is not subscriptable?

  • You will encounter TypeError: object is not subscriptable in Python when you try to use indexing on an object that is not subscriptable.
  • Since integer is not a subscriptable object, thus if you try to use indexing upon an integer object then Python will throw the following error: TypeError:'int' object is not subscriptable.

That brings us to our next questions:- What are some of the scenarios where we come across TypeError:'int' object is not subscriptable and how can we fix it?

To answer the above questions, let us visualize the occurrence and solution to this kind of TypeError with help of examples.

✨ Scenario 1: Trying To Access Index Of An Integer Object

We have already discussed the problem statement in the introduction section of this article where we tried to find the sum of all the digits of a three-digit number.

However, we got TypeError: object is not subscriptable in our futile attempt to derive the sum. The reason was: we treated the integer object num as a container object and tried to access it using its indices.

Now, it’s time to make amendments and make our program work! 😃

The Solution:

✯ Method 1: Convert Integer Object to a String Object

A simple solution to our problem is:

  • accept the user input num as a string,
  • Each digit can now be accessed using their index now as they are strings. Typecast each digit string to an integer and calculate the sum.

num = input(«Enter a 3 digit number? «)

sum_digit = (int(num[0]) + int(num[1]) + int(num[2]))

print(sum_digit)

Output:

Enter a 3 digit number? 754

16

✯ Method 2: Overwrite the __getitem__ Method

Another approach to solving the non-subscriptable TypeError is to redefine the __getitem__ method in the code itself as shown below:

class Subs:

    def __getitem__(self, item):

        return int(item)

obj = Subs()

num = input(«Enter a 3 digit number? «)

print(obj[num[0]] + obj[num[1]] + obj[num[2]])

Output:

Enter a 3 digit number? 546

15

Explanation:

In this case, we defined the __getitem__ method in our code and made it return each digit of the three-digit number in the form of an integer.

✨ Scenario 2: Treating an Integer as a List

Given below is another scenario which raises – TypeError:'int' object is not subscriptable.

item = input(«Enter item name : «)

price = input(«Enter item price : «)

x = 0

int(x[price])

discounted_Price = x3000

print («Price of an «,item, «is Rs.»,discounted_Price)

Output:

Enter item name : iPhone 12

Enter item price : 79900

Traceback (most recent call last):

  File «D:/PycharmProjects/pythonProject1/TypeError Not Subscriptable.py», line 4, in <module>

    int(x[price])

TypeError: ‘int’ object is not subscriptable

Process finished with exit code 1

In the above program, price is an integer value, however we tried to use it as a list by using its index. Thus we got the error!

The Solution:

The solution is pretty straightforward in this case. You just have to avoid using the integer object as a container type object.

item = input(«Enter item name : «)

price = input(«Enter item price : «)

x = (int(price))

discounted_Price = x 3000

print(«Price of an «, item, «is Rs.», discounted_Price)

Output:

Enter item name : iPhone 12

Enter item price : 79900

Price of an  iPhone 12 is Rs. 76900

Process finished with exit code 0

Conclusion

We learned some key points about how to deal with TypeError:'int' object is not subscriptable in Python. To avoid these errors in your code, remember:

Python raises TypeError: object is not subscriptable if you use indexing, i.e., the square bracket notation with a non-subscriptable object . To fix it you can:

  • wrap the non-subscriptable objects into a container data type as a string, list, tuple or dictionary, or,
  • by removing the index call, or
  • by defining the __getitem__ method in your code.

I hope this article helped! Please subscribe and stay tuned for more articles in the future. Happy learning! 📚

In this post, we will learn how to Fix TypeError: int object is not Subscriptable Python. The Python object strings, lists, tuples, and dictionaries are subscribable because they implement the __getitem__ method and the subscript operator [] is used to access the element by index in Python from subscriptable objects. Whereas integer is not a Subscriptable object and is used to store the whole number. An integer number can’t be accessed by index.

1. What is TypeError: int object is not Subscriptable


Whenever we perform a subscriptable objects operation on an integer like treating an integer variable as an array and accessing an element using subscript operator [] then “TypeError: int object is not Subscriptable” is encountered.

In the below example we have demonstrated TypeError: ‘int’ object is not Subscriptable, We have asked the user to input some integer value and display it using a print statement. But when we have accessed the integer value using subscript operator [] then TypeError is encountered because we are treating the integer variable as an array.

number = int(input("Please enter a integer value: "))
print("You have entered:", number)
print( number[0])

Output

print( number[0])
TypeError: 'int' object is not subscriptable
  • TypeError:NoneType object is not subscriptable
  • ValueError: Cannot convert non-finite values (NA or inf) to integer

2. Solution to TypeError:‘int’ object is not Subscriptable


In the above example, we have taken input from the user and converted it into an integer by using the python built-in function int() and tried to access it by using the Index position then we encountered with TypeError the solution for the type error not converting the input value to an integer or can be resolved by avoiding slicing and indexing while the accessed value of integer object.

number = input("Please enter a integer value: ")
print("You have enetered:", number)
print( number[0])

Output

Please enter a integer value: 36912
You have enetered: 36912
3

3. TypeError:‘int’ object is not Subscriptable Pandas


In this example, we are finding the sum of Pandas dataframe column “Marks” that has int type. While applying the Lambda function on the ‘Marks’ column using index notation or subscript operator and encountering with TypeError: ‘int’ object is not subscriptable in Pandas.

import pandas as pd
 
data = {
    'Name': ['Jack', 'Jack', 'Max', 'David'],
    'Marks':[97,97,100,100],
    'Subject': ['Math', 'Math', 'Math', 'Phy']
}
 
dfobj = pd.DataFrame(data)
print(dfobj.dtypes)
 
MarksGross = lambda x: int(x[1])
dfobj.Marks = dfobj.Marks.apply(MarksGross)

Print(dfobj.Marks.sum())

Output

  MarksGross = lambda x: int(x[1])
TypeError: 'int' object is not subscriptable

4. How to fix TypeError: int object is not Subscriptable Pandas


To solve Type Error with Pandas dataframe, We have not applied the lambda function using index notation instead use int(x) pass value of x inside () brackets.

import pandas as pd
 
data = {
    'Name': ['Jack', 'Jack', 'Max', 'David'],
    'Marks':[97,97,100,100],
    'Subject': ['Math', 'Math', 'Math', 'Phy']
}
 
dfobj = pd.DataFrame(data)
print(dfobj.dtypes)
 
MarksGross = lambda x: int(x)
dfobj.Marks = dfobj.Marks.apply(MarksGross)

print(dfobj.Marks.sum())

Output

Name       object
Marks       int64
Subject    object
dtype: object
394

Summary

In this post, we have learned how to fix TypeError: int object is not Subscriptable with examples. This error occurs when we try to access an integer variable value by index.

Typeerror int object is not subscriptable error generates because int object does not contain inner object implicitly like List etc. Actually few of the python object are subscriptable because they are a collection of few elementary objects.

Typeerror int object is not subscriptable ( Cause with Example ) –

Let’s see the root cause of this error. Because this particular error may arise in so many cases but the root cause will be the same. The way to solve it will always be the same.

var = 500
print(type(var))
subscript=var[0]

"<yoastmark

We need to check the object type before applying subscripting it. Here is an example of this.

var = 500
var_type=type(var)
print(var_type)
if(var_type!=int):
  subscript=var[0]
else:
  print("Sorry! Int object is not subscriptable")

"<yoastmark

Here we have seen that we have already checked the type of a variable before subscripting. Once we assure that this is not a subscriptable object we will bypass the code which generates this error. This is the way which helps to avoid this error.

Typeerror int object is not subscriptable (Solution)-

Well, Incase If you want to extract the last two digits of the Integer value. I know we all think to apply the subscripting. But directly doing it will raise the error int object is not subscriptable. So what’s the solution Right?

Hey! It too easy we fill firstly typecast the int variable into “str” object. Then we can do the subscripting easily.

var = 50011
var_type=type(var)
print(var_type)
if(var_type==str):
  subscript=var[-2:]
  print(subscript)
else:
  var=str(var)
  subscript=var[-2:]
  print(subscript)

Let’s run the above code and check the output.

"<yoastmark

So this the best way to Fix the error int object is not subscriptable by typecasting it into “str” object. Now we can slice it or subscript over it .

End Notes-

Well, This is one of the common errors for every python developer. I hope this exploration ( int object is not subscriptable ) works for you. In case you have some thoughts about it, please let us know via comment.

Thank You

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Posted by Marta on February 2, 2023 Viewed 11314 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

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:

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

bytes to string
tkinter progress bar
check django version
dfs in python

Some objects in Python are subscriptable. This means that they contain, or can contain, other objects. Integers are not a subscriptable object. They are used to store whole numbers. If you treat an integer like a subscriptable object, an error will be raised.

In this guide, we’re going to talk about the “typeerror: ‘int’ object is not subscriptable” error and why it is raised. We’ll walk through a code snippet with this problem to show how you can solve it in your code. Let’s begin!

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

The Problem: typeerror: ‘int’ object is not subscriptable

We’ll start by taking a look at our error message:

typeerror: 'int' object is not subscriptable

The first part of our error message, TypeError, states the type of our error. A TypeError is an error that is raised when you try to perform an operation on a value that does not support that operation. Concatenating a string and an integer, for instance, raises a TypeError.

The second part of our message informs us of the cause.

This message is telling us that we are treating an integer, which is a whole number, like a subscriptable object. Integers are not subscriptable objects. Only objects that contain other objects, like strings, lists, tuples, and dictionaries, are subscriptable.

Let’s say you try to use indexing to access an item from a list:

email_providers = ["Gmail", "Outlook", "ProtonMail"]

print(email_providers[2])

This code returns: ProtonMail. Lists are subscriptable which means you can use indexing to retrieve a value from a list.

You cannot use this same syntax on a non-subscriptable value, like a float or an integer.

An Example Scenario

We’re going to write a program that asks a user for the date on which their next holiday starts and prints out each value on a separate line. This program will have an error that we can solve.

Let’s start by writing our main program:

holiday = int(input("When does your holiday begin? (mmddyyyy) "))

month = holiday[0:2]
day = holiday[2:4]
year = holiday[4:8]

print("Month:", month)
print("Day:", day)
print("Year:", year)

This program asks a user to insert the day on which their holiday begins using an input() statement. Then, we use slicing to retrieve the values of the month, day, and year that the user has specified. These values are stored in variables.

Next, we print out the values of these variables to the console. Each value is given a label which states the part of the date to which the value corresponds.

Let’s run our code:

Traceback (most recent call last):
  File "main.py", line 3, in <module>
	month = holiday[0:1]
TypeError: 'int' object is not subscriptable

Let’s fix this error.

The Solution

We have converted the value of “holiday” into an integer. This means that we cannot access it using slicing or indexing. Integers are not indexed like strings.

To solve this problem, we can remove the int() statement from our code. The input() statement returns a string value. We can slice this string value up using our code.

Let’s revise our input() statement:

holiday = input("When does your holiday begin? (mmddyyyy) ")

Now, let’s try to run our code:

When does your holiday begin? (mmddyyyy) 02042021
Month: 02
Day: 04
Year: 2021

Our code runs successfully! We are no longer trying to slice an integer because our code does not contain an int() statement. Instead, “holiday” is stored as a string. This string is sliced using the slicing syntax.

Conclusion

The “typeerror: ‘int’ object is not subscriptable” error is raised when you try to access an integer as if it were a subscriptable object, like a list or a dictionary.

To solve this problem, make sure that you do not use slicing or indexing to access values in an integer. If you need to perform an operation only available to subscriptable objects, like slicing or indexing, you should convert your integer to a string or a list first.

Now you’re ready to solve this Python TypeError like an expert!

Понравилась статья? Поделить с друзьями:
  • Int object is not callable питон как исправить
  • Intel raid 1 volume как исправить
  • Int error python
  • Intel r visual fortran run time error
  • Int cannot be dereferenced java ошибка