How to Resolve Python "TypeError: can only concatenate tuple (not "...") to tuple"
The TypeError: can only concatenate tuple (not "X") to tuple (where "X" could be "int", "str", "list", etc.) is a common error in Python. It arises when you try to use the addition operator (+) to combine a tuple with an object of a different, incompatible type.
This guide explains why this error occurs and provides various solutions depending on your intended operation.
Understanding the Error: Concatenation Requires Compatible Types
The addition operator (+) in Python has different meanings depending on the types of objects involved:
- Numbers: Performs arithmetic addition (
1 + 2results in3). - Strings: Performs string concatenation (
'a' + 'b'results in'ab'). - Lists: Performs list concatenation (
[1] + [2]results in[1, 2]). - Tuples: Performs tuple concatenation (
(1,) + (2,)results in(1, 2)).
The TypeError: can only concatenate tuple... occurs because the + operator for tuples is only defined to work with other tuples. You can not directly "add" an integer, string, list, or other type to a tuple using +.
my_tuple = (1, 2, 3)
my_int = 4
my_str = 'hello'
my_list = [5, 6]
# These will ALL raise a TypeError:
# result = my_tuple + my_int
# result = my_tuple + my_str
# result = my_tuple + my_list