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

3D illustration of a claw failing to grasp inside a solid steel sphere, representing the 'int object is not subscriptable' error.

This error is a classic beginner mistake. You may have come across the message TypeError int not subscriptable when working with Python code.

  • “Subscriptable” means “an object that can be accessed with square brackets [].” (e.g., lists, strings, dictionaries).
  • “int object” means a number, like 5 or 123.

The error means: “You are trying to use square brackets on a plain number.”

The Cause

A number is a single value. It doesn’t have “positions” or “keys.”

Problem Code:

my_number = 12345

# Try to get the first digit
first_digit = my_number[0]
# CRASH! TypeError: 'int' object is not subscriptable

You can’t ask a number for its “zeroth” item.

The Fix: Convert to a String

If you need to access the individual digits of a number, you must first convert that number into a string. Strings are subscriptable.

my_number = 12345

# 1. Convert to string
number_as_string = str(my_number)

# 2. Now you can use brackets!
first_digit = number_as_string[0]

print(first_digit) # Output: '1'

# (Optional) Convert back to an integer
first_digit_as_int = int(first_digit)
print(first_digit_as_int) # Output: 1

This is the standard way to “pick apart” a number in Python.

Similar Posts

Leave a Reply