Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] [Solved] TypeError: ‘int’ Object Is Not Subscriptable in Python

#1
[Solved] TypeError: ‘int’ Object Is Not Subscriptable in Python

  • Python raises TypeError: object is not subscriptable if you try to use indexing upon an object that is not subscriptable. To fix it you can:
    • Typecast or wrap the non-subscriptable object to a subscriptable object like a string, list, tuple or dictionary, or,
    • Remove the index call, or
    • Overwrite the __getitem__ method in your program.

✍ Overview


https://blog.finxter.com/wp-content/uplo...300x76.png 300w, https://blog.finxter.com/wp-content/uplo...68x195.png 768w" sizes="(max-width: 805px) 100vw, 805px" />

Problem: How to fix “TypeError: ‘int’ Object Is Not Subscriptable” in Python?

Example:

number = int(input("Enter a number: "))
print("reversed num = ", number[::-1])

Output:

Enter a number: 123
Traceback (most recent call last): File "D:/PycharmProjects/PythonErrors/rough.py", line 2, in <module> print("reversed num = ", number[::-1])
TypeError: 'int' object is not subscriptable

Have you encountered this stupid error? ?

If your answer is yes, then you are not alone. This is one of the most common errors in Python, and thousands of programmers like you come across this error in numerous projects every single month. In this tutorial, you will learn exactly why this error occurs, how to fix it, and how never to make the same mistake again. So, without further delay, let’s get started.

TypeError:’int’ object is not subscriptable


Before understanding what the above mentioned TypeError means and the reason behind its occurrence; let us dive into an important question related to TypeError:’int’ object is not subscriptable.

? What does object is not Subscriptable mean in Python?


In Python, when one object can contain another object, it is subscriptable. In simple terms, subscriptable objects. Thus Stringstupleslists, and dictionaries are subscriptable objects in Python.

?Note: In Python, subscriptable objects implement the __getitem__() method. However, non-subscriptable objects like sets, integers, etc., do not have the __getitem__ attribute.

Example:

my_list = ['Python', 'Java', 'Golang']
my_set = {'Python', 'Java', 'Golang'}
my_integer = 100
print("Is list subscriptable? ", hasattr(my_list, '__getitem__'))
print("Is set subscriptable? ", hasattr(my_set, '__getitem__'))
print("Is integer subscriptable? ", hasattr(my_integer, '__getitem__'))

Output:

Is list subscriptable? True
Is set subscriptable? False
Is integer subscriptable? False

Therefore, it is clear from the above example that an integer object is not subscriptable in Python. This leads us to the next question.

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


  • Non-subscriptable objects are not indexable, like a list, tuple, or string. As soon as you try to implement indexing upon objects that are not subscriptable, you will encounter TypeError: object is not subscriptable
  • As an integer object, is not a subscriptable, thus if you try to use the index of an integer object then Python will throw the following error: TypeError:'int' object is not subscriptable.

Thus, in the above example, when we tried to access the index of an integer and then reverse it, Python raised – TypeError:'int' object is not subscriptable.

So, how do we fix this error? ? Let’s have a look at the methods to fix/avoid such errors.

? Solution 1: Typecast The Integer Object to a String Object


You can fix the error by simply converting the integer user input to a string. There are two ways of accomplishing this task:

  1. You can directly accept the user input as string, instead of an integer. However, we will not be following this method because this condition may vary according to requirements.
  2. The second way to typecast the user input from an integer to a string is to use the built-in str() method in Python.
number = int(input("Enter a number: "))
rev = str(number)
print("reversed num = ", rev[::-1])

Output:

Enter a number: 123
reversed num = 321

? Solution 2: Redefine __getitem__


Another work-around to our problem is to overwrite the __getitem__ method that takes one (index) argument i (in addition to the obligatory self argument) and returns the i-th value of the “container”.

class Rev: def __getitem__(self, i): return str(i)[::-1] obj = Rev()
number = int(input("Enter a number: "))
print(obj[number])

Output:

Enter a number: 123
321

Explanation: In our case, we are overwriting the __getitem__ method to simply return the user input as a string by reversing it using its index.

In Python, Object is Not Subscriptable error occurs in numerous scenarios. Hence, let’s have a look at some other scenarios that lead to the occurrence of a similar TypeError.

⚠ TypeError: ‘NoneType’ object is not subscriptable


The following code snippet shows the minimal example that leads to the error:

variable = None
print(variable[0])
# TypeError: 'NoneType' object is not subscriptable

Reason of Error: You set the variable to the value None. The value None is not a container object, it doesn’t contain other objects. So, the code really doesn’t make any sense—which result do you expect from the indexing operation?

Solution:

print("Method 1: Wrap the Non-Indexable values in a list")
variable = [None]
print("Output: ", variable[0])
print()
print("Method 2: Overwrite __getitem__")
class X: def __getitem__(self, i): return f"Value {i}"
variable = X()
print(variable[0])

Output:

Method 1: Wrap the Non-Indexable values in a list
Output: None Method 2: Overwrite __getitem__
Value 0

⚠ TypeError: ‘builtin_function_or_method’ object is not subscriptable


Example:

def foo(li): if li.pop['Subject'] == 'Physics': print("Every action has an equal and opposite reaction.") list1 = [{'Subject': 'Physics', 'Name': 'Newton'}, {'Subject': 'Maths', 'Name': 'Ramanujan'}, {'Subject': 'Economics', 'Name': 'Smith'}]
foo(list1)

Output:

Traceback (most recent call last): File "D:/PycharmProjects/PythonErrors/rough.py", line 9, in <module> foo(list1) File "D:/PycharmProjects/PythonErrors/rough.py", line 2, in foo if li.pop['Subject']=='Physics':
TypeError: 'builtin_function_or_method' object is not subscriptable

Solution:

Though li.pop is a valid expression in Python that results in a reference to the pop method, but in this case it doesn’t actually call that method. You need to add the open and close parentheses to call the method as shown below.

def foo(li): if li.pop(0)['Subject'] == 'Physics': print("Every action has an equal and opposite reaction.") list1 = [{'Subject': 'Physics', 'Name': 'Newton'}, {'Subject': 'Maths', 'Name': 'Ramanujan'}, {'Subject': 'Economics', 'Name': 'Smith'}]
foo(list1) # Output --> Every action has an equal and opposite reaction.

⚠ TypeError: ‘set’ object is not subscriptable


The following code snippet shows the minimal example that leads to the error:

my_set = {111, 222, 333}
print(my_set[2]) # TypeError: 'set' object is not subscriptable

Reason: set is not a subscriptable object in Python. Hence, you cannot access its elements using their index.

Solution:

  1. Convert the set to a list, or,
  2. overwrite the __getitem__ method.
my_set = {111, 222, 333} # Method 1
my_list = list(my_set)
print("Method 1 Output: ", my_list[2]) # Method 2
class Convert: def __getitem__(self, i): return [*i, ][2] obj = Convert()
print("Method 2 Output: ", obj[my_set])

Output:

Method 1 Output: 111
Method 2 Output: 111

Conclusion


Here are some recommended articles that might help you further:

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

The Complete Guide to PyCharm

  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!

The post [Solved] TypeError: ‘int’ Object Is Not Subscriptable in Python first appeared on Finxter.



https://www.sickgaming.net/blog/2021/03/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] How to Determine the Type of an Object in Python? xSicKxBot 0 19 04-06-2021, 07:26 PM
Last Post: xSicKxBot
  [Tut] [Solved] NumPy RuntimeWarning: All-NaN slice encountered xSicKxBot 0 14 04-02-2021, 11:10 AM
Last Post: xSicKxBot
  [Tut] [Solved] TypeError: ‘Module’ Object Is Not Callable in Python xSicKxBot 0 19 03-25-2021, 08:09 PM
Last Post: xSicKxBot
  [Tut] Python Celery – How to Get a Task Result Object by ID? xSicKxBot 0 16 03-18-2021, 06:52 PM
Last Post: xSicKxBot
  [Tut] Python object() Function xSicKxBot 0 67 02-16-2021, 08:16 PM
Last Post: xSicKxBot
  [Tut] How to Check if an Object is of Type List in Python? xSicKxBot 0 53 02-09-2021, 08:05 AM
Last Post: xSicKxBot
  [Tut] How to Fix “TypeError: len() of unsized object” xSicKxBot 0 59 01-31-2021, 12:55 PM
Last Post: xSicKxBot
  [Tut] Python help() xSicKxBot 0 65 01-22-2021, 01:02 AM
Last Post: xSicKxBot
  [Tut] How to Get The Current Reference Count of an Object in Python? xSicKxBot 0 67 12-21-2020, 08:13 AM
Last Post: xSicKxBot
  [Tut] Python complex() — A Useless Python Feature? xSicKxBot 0 73 12-19-2020, 02:05 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
[Tut] How to Display an Image as Graysca...
Last Post: xSicKxBot
Today 09:01 PM
» Replies: 0
» Views: 0
(Indie Deal) SNK's Metal Slug, King of F...
Last Post: xSicKxBot
Today 09:01 PM
» Replies: 0
» Views: 0
Xbox Wire - Monster Train: The Last Divi...
Last Post: xSicKxBot
Today 09:00 PM
» Replies: 0
» Views: 0
News - Wargaming opens Lithuania studio ...
Last Post: xSicKxBot
Today 09:00 PM
» Replies: 0
» Views: 1
News - Get a job: Join Volition as a Sen...
Last Post: xSicKxBot
Today 09:00 PM
» Replies: 0
» Views: 0
PluralSight Courses All Free During Apri...
Last Post: xSicKxBot
Today 05:10 PM
» Replies: 0
» Views: 6
AppleInsider - Flash deal: 50% off H&R B...
Last Post: xSicKxBot
Today 05:10 PM
» Replies: 0
» Views: 6
News - See More Of New Zombie Game The D...
Last Post: xSicKxBot
Today 05:09 PM
» Replies: 0
» Views: 5
ISO: Staff Members for Website, Discord,...
Last Post: Ronalddiz
Today 04:20 PM
» Replies: 4
» Views: 8459
Official Sick Gaming Social Links: Twitt...
Last Post: Marcusjut
Today 09:56 AM
» Replies: 5
» Views: 9843

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020