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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

The Python "TypeError: can only concatenate tuple (not "int") to tuple" occurs when we try to concatenate a tuple and an integer. To solve the error, make sure you haven't got any dangling commas if trying to sum two integers, otherwise declare 2 tuples.

typeerror can only concatenate tuple not int to tuple

Here is an example of how the error occurs.

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

We tried to use the addition (+) operator to concatenate a tuple and an integer which caused the error.

The values on the left and right-hand sides need to be of compatible types.

If you meant to concatenate two tuples, declare a tuple instead of an int.

main.py
my_tuple = 1, 2, 3 my_other_tuple = (4,) result = my_tuple + my_other_tuple print(result) # 👉️ (1, 2, 3, 4)
If you meant to add 2 integers, make sure you don't have any dangling commas as you might be declaring a tuple by mistake.

Tuples are constructed in multiple ways:

  • Using a pair of parentheses () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor

If you meant to access an element at a specific index in the tuple, use square brackets.

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

We accessed the first element in the tuple and added it to an integer. Note that the values on both sides of the addition operator are integers, so this is allowed.

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

main.py
my_tuple = (1, 2, 3) print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ True my_int = 10 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 tuple (not "int") to tuple" occurs when we try to concatenate a tuple and an integer. To solve the error, make sure you haven't got any dangling commas if trying to sum two integers, otherwise declare 2 tuples.

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.