Skip to main content

Solve TypeError: ‘int’ object is not subscriptable in Python Gorakh Gupta The Crazy Programmer

While we are using the operator on a string there an integer value will raise TypeError. We can say it in other words as the TypeError is raised on an unsupported object type when we are applying an operation of the wrong type. This error generally occurs when we are trying to use the integer type value as an array.

In python language when any type of object that implements the get_item method then the class definition is being called subscriptable objects and when we are applying the method by which we can access the elements of the object for getting the value.

In this article, we are going to see what is the reason for this error and how can we overcome this type of error in programs.

Reasons for Error

Case 1:

Suppose we want to write a program to calculate your number for the car which is based on the date of joining a company.

date_of_joining = '15/07/2000'

add_month_values = (int(date_of_joining[0])+int(date_of_joining[1]))
add_day_values = (int(date_of_joining[3])+int(date_of_joining[4]))
add_year_values= (int(date_of_joining[6])+
int(date_of_joining[7])+int(date_of_joining[8])+int(date_of_joining[9]))

add_all = add_month_values + add_day_values + add_year_values
car_number= (int(add_all[0])+int(add_all[1]))

print("car_number is", car_number)

In the above example, we have written a variable named date_of_joining which is in the format of dd/mm/yyyy and then we will be adding up the digits of total. Like there is an example:

Date of joining: 15/07/2000
1+5+7+2=15
1+5=6
Car_number is 6

Total addition is add of month digits, day digits, and year digits.

Then car_number is the sum of the total sum.

It will throw an error called as int object is not subscriptable.

Traceback (most recent call last):
  File "c:\Users\91930\Documents\work\tempCodeRunnerFile.py", line 1, in <module>
car_number= (int(add_all[0])+int(add_all[1]))

NameError: name ‘birthday’ is not defined and an error will occur at line 7 as the reason for the error is that the variable name add_all is a type of integer not a type of string. We cannot treat this variable as an array like storage for numbers and we should try to access each number. To fix this error, I will convert the add_all  variable to a string value and then we will use the str for finding the digits.

car_number= (int(str(add_all)[0])+int(str(add_all)[1]))

String type is a container like that we can access each character of string using index access.

Here is an example:

variable_string="cricket"
print(variable_string[4])

Output:

PS C:\Users\91930\Documents\work> python -u "c:\Users\91930\Documents\work\tempCodeRunnerFile.py"
k

Case 2:

Suppose we want to write a program in which we print product price as an array.

FruitName = input("Enter Fruit name : ")
FruitPrice = input("Enter Fruit price : ")
x = 0
int(x[FruitPrice])
FruitPriceAfterDiscount = 200 - x
print (FruitName + " is available for Rs. " + FruitPriceAfterDiscount + " .")

In the given code, we have given the integer value as the variable name as  ‘Fruit_Price’, but in the print statement, we are trying to use it as an array. We will provide the user input fruit name and the fruit price. Now we will give the value of the fruit price to the variable x in the int format. Calculate the price after the discount.

Output:

Enter Fruit name : apple
Enter Fruit price : 120
Traceback (most recent call last):
  File "c:\Users\91930\Documents\work\tempCodeRunnerFile.py", line 4, in <module>
    int(x[FruitPrice])
TypeError: 'int' object is not subscriptable

Solutions for Error

Case 1:

To solve this error you have to avoid using integer values as an array. We have converted the value of birthday into an integer and this means that we cannot access it using indexing. So now birth date will be the type of string so that we can use slicing and indexing on the string variable as usual. Integers are usually not indexed as strings.

To solve the problem,  we can do one thing we will remove the int() statement from our code. The input() statement usually always returns a string value. We can also slice this string value by using the main code.

Lets recall our main input statement:

car_number= (int(add_all[0])+int(add_all[1]))

To remove the error we will put input instead of int and our code will work successfully. We will no longer trying to slice the integer because our code will not contain any int statement further. Instead “Birthday” is stored as a string. The string is now sliced using the slicing index.

car_number= (input(add_all[0])+input(add_all[1]))

Revised Code:

date_of_joining = '15/07/2000'

add_month_values = (input(date_of_joining[0])+input(date_of_joining[1]))
add_day_values = (input(date_of_joining[3])+input(date_of_joining[4]))
add_year_values= (input(date_of_joining[6])+
input(date_of_joining[7])+input(date_of_joining[8])+input(date_of_joining[9]))

add_all = add_month_values + add_day_values + add_year_values

car_number= (input(add_all[0])+input(add_all[1]))

print("car_number is", car_number)

Output:

> python -u "c:\Users\91930\Documents\work\article1.py"
1
5
0
7
2
0
0
0

Case 2:

To solve this error we will not any integer as an array for any value. Earlier we have assigned an integer value to the variable ‘FruitPrice’, but we are trying to use it as an array in the print statement. When we are revising the code then we are removing the variable x=0 and then we are giving it x=int(FruitPrice) and after giving the value of product price to the variable x in int format and then calculating the price after discount .after all this we are printing the output.

Recessing the code after the change as:

FruitName = input("Enter Fruit name : ")
FruitPrice = input("Enter Fruit price : ")
x = int(x[FruitPrice])
FruitPriceAfterDiscount = x - 200
print (FruitName + " is available for Rs. " + str(FruitPriceAfterDiscount) + " after discount.")

Output:

PS C:\Users\91930\Documents\work> python -u "c:\Users\91930\Documents\work\article1.py"
Enter Fruit name : apple
Enter Fruit price : 400
apple is available for Rs. 200 after discount.

Conclusion

We have to use a sensible and a meaningful variable name when we are giving in the code. We should always give other name of the variables so that will tell about the data they look on. We should never use a variable name as same as python in-built function name, module name, and constants. The false value “TypeError: int object is not subscriptable” error is being arised as because when you access an integer as if it will only give a particular subscriptable object just like a list or a dictionary etc.

The error is saying that when we are treating an integer which will be a whole number as like a subscriptable object. Likely integers are not subscriptable objects as only objects are that contain other objects like strings, lists, tuples, and dictionaries are subscriptable. We cannot use the same syntax on a non-subscripatble value like a float or an integer as lists are subscriptable which means we can only use indexing to retrieve a value from a list.

Lastly when we are meeting this type of error then it is important to check many times so that to be accessed by index, the square bracket and make well sure when we are just using this against the container variables which will be done by such as containers. The false value can be only corrected by removing several types of indexing to find the values of the int object. Whenever it comes we need to apply indexing on the int object we first need to convert that into strings and then we will perform this method to solve all the issues.

The post Solve TypeError: ‘int’ object is not subscriptable in Python appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/KMVr0bn

Comments

Popular posts from this blog

Difference between Web Designer and Web Developer Neeraj Mishra The Crazy Programmer

Have you ever wondered about the distinctions between web developers’ and web designers’ duties and obligations? You’re not alone! Many people have trouble distinguishing between these two. Although they collaborate to publish new websites on the internet, web developers and web designers play very different roles. To put these job possibilities into perspective, consider the construction of a house. To create a vision for the house, including the visual components, the space planning and layout, the materials, and the overall appearance and sense of the space, you need an architect. That said, to translate an idea into a building, you need construction professionals to take those architectural drawings and put them into practice. Image Source In a similar vein, web development and design work together to create websites. Let’s examine the major responsibilities and distinctions between web developers and web designers. Let’s get going, shall we? What Does a Web Designer Do?

A guide to data integration tools

CData Software is a leader in data access and connectivity solutions. It specializes in the development of data drivers and data access technologies for real-time access to online or on-premise applications, databases and web APIs. The company is focused on bringing data connectivity capabilities natively into tools organizations already use. It also features ETL/ELT solutions, enterprise connectors, and data visualization. Matillion ’s data transformation software empowers customers to extract data from a wide number of sources, load it into their chosen cloud data warehouse (CDW) and transform that data from its siloed source state, into analytics-ready insights – prepared for advanced analytics, machine learning, and artificial intelligence use cases. Only Matillion is purpose-built for Snowflake, Amazon Redshift, Google BigQuery, and Microsoft Azure, enabling businesses to achieve new levels of simplicity, speed, scale, and savings. Trusted by companies of all sizes to meet

2022: The year of hybrid work

Remote work was once considered a luxury to many, but in 2020, it became a necessity for a large portion of the workforce, as the scary and unknown COVID-19 virus sickened and even took the lives of so many people around the world.  Some workers were able to thrive in a remote setting, while others felt isolated and struggled to keep up a balance between their work and home lives. Last year saw the availability of life-saving vaccines, so companies were able to start having the conversation about what to do next. Should they keep everyone remote? Should they go back to working in the office full time? Or should they do something in between? Enter hybrid work, which offers a mix of the two. A Fall 2021 study conducted by Google revealed that over 75% of survey respondents expect hybrid work to become a standard practice within their organization within the next three years.  Thus, two years after the world abruptly shifted to widespread adoption of remote work, we are declaring 20