Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
The Python "TypeError: can only concatenate tuple (not "list") to tuple" occurs when we try to concatenate a tuple and a list. To solve the error, make sure the two values are of type list or of type tuple before concatenating them.
Here is an example of how the error occurs.
my_tuple = ('a', 'b') my_list = ['c', 'd'] # ⛔️ TypeError: can only concatenate tuple (not "list") to tuple result = my_tuple + my_list
We tried to use the addition (+) operator to concatenate a tuple and a list which caused the error.
If you meant to concatenate two tuples, declare a tuple instead of a list, or convert the list to a tuple.
my_tuple = ('a', 'b') my_list = ['c', 'd'] result = my_tuple + tuple(my_list) print(result) # 👉️ ('a', 'b', 'c', 'd')
We converted the list to a tuple and concatenated the two tuples.
Conversely, you can convert the tuple into a list and concatenate the two lists.
my_tuple = ('a', 'b') my_list = ['c', 'd'] result = list(my_tuple) + my_list print(result) # 👉️ ['a', 'b', 'c', 'd']
If you declared the tuple by mistake, tuples are constructed in the following ways:
()
creates an empty tuplea,
or (a,)
a, b
or (a, b)
tuple()
constructorIf you meant to append the tuple to a list, use the append()
method.
my_tuple = ('c', 'd') my_list = [('a', 'b')] my_list.append(my_tuple) print(my_list) # 👉️ [('a', 'b'), ('c', 'd')]
The list.append() method adds an item to the end of the list.
The method returns None
as it mutates the original list.
If you aren't sure what type a variable stores, use the built-in type()
class.
my_tuple = ('a', 'b') print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ True my_list = ['c', 'd'] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ 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.