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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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

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

typeerror can only concatenate tuple not float to tuple

Here is an example of how the error occurs.

main.py
my_tuple = 1.1, 2.2 my_float = 3.3 # ⛔️ TypeError: can only concatenate tuple (not "float") to tuple result = my_tuple + my_float

We tried to use the addition (+) operator to concatenate a tuple and a float 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 float.

main.py
my_tuple = 1.1, 2.2 my_other_tuple = (3.3,) result = my_tuple + my_other_tuple print(result) # 👉️ (1.1, 2.2, 3.3)
If you meant to add 2 floats, 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.1, 2.2 my_float = 3.3 result = my_tuple[0] + my_float print(result) # 👉️ 4.4

We accessed the first element in the tuple and added it to a float. Note that the values on both sides of the addition operator are floats, 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.1, 2.2) print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ True my_float = 3.3 print(type(my_float)) # 👉️ <class 'float'> print(isinstance(my_float, float)) # 👉️ 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 "float") to tuple" occurs when we try to concatenate a tuple and a float. To solve the error, make sure you haven't got any dangling commas if trying to sum two floats, 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.