float() argument must be a string or a real number, not list

avatar

Borislav Hadzhiev

Wed Apr 20 20221 min read

float() argument must be a string or a real number, not list #

The Python "TypeError: float() argument must be a string or a real number, not 'list'" occurs when we pass a list to the float() class. To solve the error, access a specific item in the list and pass the item to the float() class, e.g. float(my_list[0]).

float argument must be a string or real number not list

Here is an example of how the error occurs.

main.py
my_list = ['1.1', '2.2', '3.3'] # ⛔️ TypeError: float() argument must be a string or a real number, not 'list' result = float(my_list)

We passed an entire list to the float() class which caused the error.

One way to solve the error is to access the list at a specific index and pass the item to the float() class.

main.py
my_list = ['1.1', '2.2', '3.3'] result = float(my_list[0]) print(result) # 👉️ 1.1
Indices are 0 based, so the first item in the list has an index of 0, and the last - an index of -1.

If you meant to convert all items in the list to floating-point numbers, use a list comprehension.

main.py
my_list = ['1.1', '2.2', '3.3'] new_list = [float(x) for x in my_list] print(new_list) # 👉️ [1.1, 2.2, 3.3]

We pass each string in the list to the float() class to convert each item to an integer.

Alternatively, you can use the map() function.

main.py
my_list = ['1.1', '2.2', '3.3'] new_list = list(map(float, my_list)) print(new_list) # 👉️ [1.1, 2.2, 3.3]

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

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