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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

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

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.

typeerror can only concatenate tuple not list to tuple

Here is an example of how the error occurs.

main.py
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.

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 a list, or convert the list to a tuple.

main.py
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.

main.py
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:

  • Using a pair of parenthesis () 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 append the tuple to a list, use the append() method.

main.py
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.

main.py
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.

Use the search field on my Home Page to filter through my more than 3,000 articles.