TypeError: can only concatenate list (not "int") to list

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: can only concatenate list (not "int") to list #

The Python "TypeError: can only concatenate list (not "int") to list" occurs when we try to concatenate a list and an integer. To solve the error, use the append() method to add an item to the list, e.g. my_list.append(123).

typeerror can only concatenate list not int to list

Here is an example of how the error occurs.

main.py
my_list = [1, 2, 3] my_int = 4 # ⛔️ TypeError: can only concatenate list (not "int") to list result = my_list + my_int

We tried to use the addition (+) operator to add an item to a list which caused the error.

You can use the append() method to add an item to a list.

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

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

The method returns None as it mutates the original list.

Alternatively, you can wrap the integer in a list if you'd prefer to use the addition (+) operator.

main.py
my_list = [1, 2, 3] my_int = 4 result = my_list + [my_int] print(result) # 👉️ [1, 2, 3, 4]

However, using the append() method is much more common.

Conversely, if you need to remove an item from a list, use the remove() method.

main.py
my_list = [1, 2, 3] my_int = 3 my_list.remove(my_int) print(my_list) # 👉️ [1, 2]

The list.remove() method removes the first item from the list whose value is equal to the passed in argument.

The method raises a ValueError if there is no such item.

The remove() method mutates the original list and returns None.

If you meant to add a specific item in the list to an integer, access the item at its index using square brackets.

main.py
my_list = [1, 2, 3] my_int = 3 result = my_list[0] + 3 print(result) # 👉️ 4

We accessed the list item at index 0 and added it to the integer stored in the my_int variable.

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
my_list = [1, 2, 3] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True my_int = 3 print(type(my_int)) # 👉️ <class 'int'> print(isinstance(my_int, int)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Conclusion #

The Python "TypeError: can only concatenate list (not "int") to list" occurs when we try to concatenate a list and an integer. To solve the error, use the append() method to add an item to the list, e.g. my_list.append(123).

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.