TypeError: 'int' Object Is Not Subscriptable – Causes, Fixes, and Examples
The TypeError: 'int' object is not subscriptable is a common error in Python that occurs when you attempt to index or slice an integer, which is not allowed. This error typically arises from misunderstandings about data types or incorrect variable assignments. This guide explains why this error happens, how to fix it, and provides practical examples to help you avoid it in your Python projects Not complicated — just consistent..
Introduction
Python is a dynamically typed language, meaning variables can hold different types of data (e.Here's the thing — g. , integers, strings, lists). That said, certain operations are only valid for specific data types. Because of that, for example, indexing (accessing elements via square brackets) works for lists, strings, and tuples but not for integers. When you try to index an integer, Python raises a TypeError because integers are not subscriptable. Understanding this error is crucial for writing dependable and error-free code Most people skip this — try not to. Less friction, more output..
Common Causes of the Error
Here are the most frequent scenarios that trigger this error:
1. Indexing an Integer Directly
If you try to access an element of an integer using square brackets, Python will raise this error Less friction, more output..
x = 5
print(x[0]) # TypeError: 'int' object is not subscriptable
2. Incorrect Variable Assignment
Sometimes, a variable is assigned an integer when a list or string is expected Simple as that..
data = 42
print(data[1]) # Error! data is an integer, not a list
3. Function Return Values
A function might return an integer instead of a list or string, leading to the error when indexed.
def get_value():
return 10
result = get_value()
print(result[0]) # Error! result is an integer
4. User Input Handling
User input is often read as a string, but if converted to an integer, indexing becomes impossible Easy to understand, harder to ignore..
user_input = int(input("Enter a number: "))
print(user_input[0]) # Error! user_input is an integer
How to Fix the Error
To resolve this error, follow these steps:
Step 1: Check Variable Types
Use the type() function to verify the data type of your variable Worth knowing..
x = 5
print(type(x)) # Output:
Step 2: Ensure Correct Data Structures
If you need to index data, ensure the variable is a subscriptable type like a list, string, or tuple But it adds up..
x = 5
x_str = str(x) # Convert to string
print(x_str[0]) # Output: '5'
x_list = [5] # Convert to list
print(x_list[0]) # Output: 5
Step 3: Use Type Conversion
Convert integers to strings or lists if indexing is required.
number = 123
number_str = str(number)
print(number_str[0]) # Output: '1'
Step 4: Debug Function Returns
Review functions to ensure they return the correct data type.
def get_data():
return [1, 2, 3] # Return a list instead of an integer
data = get_data()
print(data[0]) # Output: 1
Step 5: Handle User Input Properly
If user input is read as an integer, convert it to a string for indexing.
user_input = input("Enter a number: ") # Read as string
print(user_input[0]) # Works!
Practical Examples
Example 1
Example 1
Imagine a program that tracks the highest score achieved by a player. The original list is fine, but later the same identifier is reassigned to an integer, causing the indexing operation to fail.
scores = [85, 92, 78] # a list of results
best = scores[0] # works – best is 85
best = 100 # accidental reassignment; best is now an int
print(best[0]) # TypeError: 'int' object is not subscriptable
Why it breaks – after the second assignment best ceases to be a list, so the square‑bracket operator has nothing to interpret as a sequence.
Fix – keep the original container untouched and use a distinct name for the derived value:
scores = [85, 92, 78]
top_score = scores[0] # retain the list
print(top_score) # 85
If you need to store a single numeric result, choose a non‑conflicting identifier such as max_score.
Example 2
A common pitfall appears when a dictionary is treated as if it were a list. Dictionaries are subscriptable, but only with keys, not with numeric positions.
player = {"name": "Ada", "score": 42}
print(player[0]) # TypeError: 'dict' object is not subscriptable
Resolution – retrieve the desired value by its key, or convert the dictionary’s keys to a list first:
player = {"name": "Ada", "score": 42}
print(player["score"]) # 42
# or, if you really need positional access:
positions = list(player.keys())
print(positions[0]) # 'name'
Example 3
Functions sometimes return a primitive type instead of the container you expect. When the returned value is immediately indexed, the error surfaces That's the whole idea..
def get_first_item():
return 7 # an int, not a list
first = get_first_item()[0] # TypeError: 'int' object is not subscriptable
Remedy – make the function return a proper sequence, or unpack the result appropriately:
def get_first_item():
return [7] # now a list
first = get_first_item()[0] # 7 – works as intended
Alternatively, if the function should yield a single value, avoid indexing altogether:
def get_first_item():
return 7 # return the integer directly
first = get_first_item() # 7 – no indexing needed
Conclusion
The “not subscriptable” message signals a mismatch between the data type stored in a variable and the subscript operation you are attempting. By systematically verifying the actual type of each variable, ensuring that lists, strings, tuples, or dictionaries are present where indexing is required, and converting or restructuring data when necessary, you can eliminate this error from your codebase. Additionally, careful attention to function return values and the handling of user‑provided input prevents accidental type shifts that would otherwise trigger the same exception. Applying these checks consistently leads to more dependable, maintainable Python programs.
Easier said than done, but still worth knowing.
Defensive Programming Strategies
Beyond spotting the immediate type mismatch, adopting a few defensive habits can keep “not subscriptable” errors from surfacing in the first place The details matter here. And it works..
-
Explicit Type Annotations
Adding type hints makes expectations clear to both humans and static analysers.def get_scores() -> list[int]: return [85, 92, 78] scores: list[int] = get_scores() top_score = scores[0] # ✅ safe -
Runtime Checks with
isinstance
When data originates from external sources (JSON, user input, APIs), verify the container type before indexing.import json raw = await fetch_user_profile() # might be a dict or a list data = json.loads(raw) if isinstance(data, dict): name = data.get("name") elif isinstance(data, list): name = data[0] if data else None else: raise TypeError(f"Unexpected payload type: {type(data)}") -
make use of
getandtry/exceptfor Dictionaries
Dictionaries raise aKeyErrorfor missing keys, which is often preferable to a cryptic subscript error.player = {"name": "Ada", "score": 42} score = player.get("score") # returns None if key absent if score is None: # handle missing value gracefully -
Use Slicing for Safe Access
Slicing never raises an error; it simply returns an empty sequence when indices are out of range.scores = [85, 92] first_two = scores[:2] # works even if scores has <2 elements -
Encapsulate Indexing in Helper Functions
Centralising the access logic reduces duplication and makes it easier to change the underlying data structure later That alone is useful..def safe_get(seq, idx, default=None): return