AttributeError: 'int' object has no attribute 'append'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

AttributeError: 'int' object has no attribute 'append' #

The Python "AttributeError: 'int' object has no attribute 'append'" occurs when we call the append() method on an integer. To solve the error, make sure the value you are calling append on is of type list.

attributeerror int object has no attribute append

Here is an example of how the error occurs.

main.py
my_list = ['a', 'b', 'c'] # 👇️ reassign variable to integer my_list = 10 print(type(my_list)) # 👉️ <class 'int'> # ⛔️ AttributeError: 'int' object has no attribute 'append' my_list.append('d')

We reassigned the my_list variable to an integer and tried to call the append() method on the integer which caused the error.

If you print() the value you are calling append() on, it will be an integer.

To solve the error, you need to track down where exactly you are setting the value to an integer in your code and correct the assignment.

To solve the error in the example, we would have to remove the reassignment or correct it.

main.py
my_list = ['a', 'b', 'c'] my_list.append('d') print(my_list) # 👉️ ['a', 'b', 'c', 'd']

The append() method adds an item to the end of a list.

Calling the method on an integer causes the error.

Make sure you aren't trying to access the list at a specific index when calling append.

main.py
fav_numbers = [1, 2, 3] # ⛔️ AttributeError: 'int' object has no attribute 'append' fav_numbers[0].append(4) print(fav_numbers)

The fav_numbers variable stores a list of numbers.

We accessed the list item at index 0 (which is the integer 1) and called the append() method on the result which caused the error.

To solve the error in this scenario, remove the index accessor and call the append() method on the list.

main.py
fav_numbers = [1, 2, 3] fav_numbers.append(4) print(fav_numbers) # 👉️ [1, 2, 3, 4]

You might also be assigning the result of calling a function that returns an integer to a variable.

main.py
def get_list(): return 100 my_list = get_list() # ⛔️ AttributeError: 'int' object has no attribute 'append' my_list.append('d')

The my_list variable gets assigned to the result of calling the get_list function.

The function returns an integer, so we aren't able to call append() on it.

To solve the error, you have to track down where the specific variable gets assigned an integer instead of a list and correct the assignment.

Conclusion #

The Python "AttributeError: 'int' object has no attribute 'append'" occurs when we call the append() method on an integer. To solve the error, make sure the value you are calling append on is of type list.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.