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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Check out my new book

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

The Python "TypeError: can only concatenate list (not "float") to list" occurs when we try to concatenate a list and a floating-point number. To solve the error, use the append() method to add an item to the list, e.g. my_list.append(3.3).

typeerror can only concatenate list not float to list

Here is an example of how the error occurs.

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

We tried to use the addition (+) operator to add an item to a list which caused the error.

You can use the append() method to add an item to a list.

main.py
my_list = [1.1, 2.2] my_float = 3.3 my_list.append(my_float) print(my_list) # 👉️ [1.1, 2.2, 3.3]

The list.append() method adds an item to the end of the list.

The method returns None as it mutates the original list.

Alternatively, you can wrap the float in a list if you'd prefer to use the addition (+) operator.

main.py
my_list = [1.1, 2.2] my_float = 3.3 result = my_list + [my_float] print(result) # 👉️ [1.1, 2.2, 3.3]

However, using the append() method is much more common.

Conversely, if you need to remove an item from a list, use the remove() method.

main.py
my_list = [1.1, 2.2] my_float = 2.2 my_list.remove(my_float) print(my_list) # 👉️ [1.1]

The list.remove() method removes the first item from the list whose value is equal to the passed in argument.

The method raises a ValueError if there is no such item.

The remove() method mutates the original list and returns None.

If you meant to add a specific item in the list to a float, access the item at its index using square brackets.

main.py
my_list = [1.1, 2.2] my_float = 3.3 result = my_list[0] + my_float print(result) # 👉️ 4.4

We accessed the list item at index 0 and added it to the float stored in the my_float variable.

If you aren't sure what type of object a variable stores, use the built-in type() class.

main.py
my_list = [1.1, 2.2] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ 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.

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.