How to Resolve Python "AttributeError: 'int' object has no attribute '...'"
Fix the Python AttributeError when trying to use list or string methods like append, split, or encode on an integer by identifying type mismatches and correcting variable assignments.
The AttributeError: 'int' object has no attribute '...' (where ... is a method or property name like append, split, lower, etc.) is a frequent error in Python. It signals a fundamental type mismatch: you are trying to use a feature (an attribute or method) that belongs to a different data type (like a list, string, or custom object) on a variable that currently holds an integer (int).
This guide explains why this happens and how to fix it, covering common examples like append, split, and encode.
Understanding the Error: Type Mismatch
Python is dynamically typed, meaning a variable's type can change during program execution. However, operations you perform on a variable must be valid for its current type.
An AttributeError occurs when you try to access an attribute (a variable associated with an object) or call a method (a function associated with an object) that doesn't exist for that object's type.
Integers (int) in Python have specific attributes and methods (mostly related to numerical operations), but they do not have methods like append() (which belongs to lists) or split() (which belongs to strings).
Common Cause: Incorrect Variable Assignment
The most frequent reason for this error is that a variable you expect to hold a certain type (e.g., a list or str) has been accidentally reassigned to hold an int somewhere earlier in your code.
my_data = [10, 20, 30]print(f"Initially: {my_data}, type: {type(my_data)}")my_data = len(my_data) # len() returns an integer (3 in this case)print(f"After reassignment: {my_data}, type: {type(my_data)}")try: my_data.append(40)except AttributeError as e: print(e)
Another common cause is assigning the return value of a function that you thought returned one type (like a string) but actually returned an integer.
Debugging: Identifying the Type Mismatch
When you encounter this error, the first step is to confirm the type of the variable right before the line causing the error.
variable_causing_error = 123 # Example valueprint(f"Type of variable_causing_error: {type(variable_causing_error)}")try: variable_causing_error.some_method()except AttributeError as e: print(f"Error: {e}")
Once you confirm it's an int, trace back through your code (or use a debugger) to find where that variable was assigned the integer value instead of the expected type.
General Solution: Fix Assignment or Convert Type
Primary Solution: Fix the Assignment: The best approach is usually to find the incorrect assignment and fix it so the variable holds the correct type (e.g., list, string) when the method is called.
Secondary Solution: Type Conversion: If the logic requires you to work with the number but use a method from another type, you might explicitly convert the intjust before calling the method. This is common when needing string methods on numbers.
number = 12345if str(number).startswith('123'): print("Number starts with '123'")
However, this only works if the operation makes sense after conversion (e.g., you can't meaningfully append to a converted number).
Specific Examples and Solutions
AttributeError: 'int' object has no attribute 'append' (List Method)
This error means you called .append() on an integer. append() is exclusively a list method used to add items to the end of a list.
Error Cause: The variable is an int, not a list.
my_list = [1, 2]my_list = 5 # ⚠️ Incorrect assignmenttry: my_list.append(3)except AttributeError as e: print(e)number_list = [10, 20, 30]try: number_list[0].append(5)except AttributeError as e: print(e) # Output: 'int' object has no attribute 'append'
Solution: Ensure the variable is a list when .append() is called. Fix any incorrect assignments or logic errors.
AttributeError: 'int' object has no attribute 'encode' (String Method)
This error happens when you call .encode() on an integer. encode() is a str method used to convert a string into a bytes object using a specified encoding (like UTF-8).
Solution: Ensure the variable is a str. Fix assignments or convert the int to str before encoding if you intend to encode the number's string representation.
Other Common Methods (e.g., isdigit, startswith, lower)
The same principle applies to any method specific to strings (isdigit, startswith, endswith, lower, upper, strip, etc.) or other types. If you call them on an int, you'll get the AttributeError.
Error Cause: Calling a string-specific method on an int.
value = 123try: is_digit = value.isdigit()except AttributeError as e: print(e)
Solution: Convert to str before calling the method, or ensure the variable holds a str in the first place.
value = 123is_digit = str(value).isdigit()print(is_digit) # Output: True
Using hasattr() for Defensive Programming
While fixing the root cause is best, you can sometimes use the built-in hasattr() function to check if an object has a specific attribute/method before attempting to access it. This can prevent the error but might hide the underlying logic flaw.
variable = 123 # Could be an int or something elseif hasattr(variable, 'append'): variable.append(4) print("Appended successfully")elif hasattr(variable, 'lower'): print(f"String in lower case: {variable.lower()}")else: print(f"Variable is of type {type(variable)} and doesn't have expected methods.")
Using dir() to Inspect Available Attributes
To see exactly which attributes and methods are available for an object (like an integer), you can use the dir() function. This is useful for debugging and understanding what operations are valid.
number = 10print(dir(number))
Output includes things like (notice the absence of 'append', 'split', 'encode', etc.):
The AttributeError: 'int' object has no attribute '...' in Python is a clear sign that you're trying to perform an operation on an integer that isn't valid for its type.
The most reliable solution is to:
Use print(type(variable)) to confirm the type just before the error occurs.
Trace back and fix the code where the variable was incorrectly assigned an integer value.
Alternatively, if logically necessary, explicitly convert the integer to the required type (e.g., str()) immediately before calling the method.
By understanding the type requirements of different methods, you can effectively debug and prevent these common errors.