Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Timothy Meinberg
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.
Here is an example of how the error occurs.
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.
If you meant to concatenate two tuples, declare a tuple instead of an int.
my_tuple = 1, 2, 3 my_other_tuple = (4,) result = my_tuple + my_other_tuple print(result) # 👉️ (1, 2, 3, 4)
Tuples are constructed in multiple ways:
()
creates an empty tuplea,
or (a,)
a, b
or (a, b)
tuple()
constructorIf you meant to access an element at a specific index in the tuple, use square brackets.
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.
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.