How to Resolve Python TypeError: float() argument must be a string or a real number, not 'X'
The TypeError: float() argument must be a string or a real number, not 'X' (where 'X' is often list, NoneType, method, etc.) is a common Python error. It occurs when you attempt to use the float() constructor to convert an object that isn't a valid string representation of a number or an actual numeric type (like int).
This guide explains the common causes for different types (list, NoneType, method) and provides practical solutions.
Understanding the Error: float() Requirements
The built-in float() function is used to:
- Convert a compatible string (like
"3.14","100","-5.5e-1") into a floating-point number. - Convert an integer (
int) into a floating-point number.
It can not directly convert complex data structures like lists, dictionaries, or special objects like None or methods themselves into a single float. You must first extract or provide a valid string or number from these objects.
Handling ... not 'list'
Cause: You passed an entire list object to float().
# Error Example:
my_list = ['1.1', '2.2', '3.3']
result = float(my_list) # ⛔️ TypeError: ... not 'list'
Solution: Access a List Element
If you intended to convert a specific item within the list, access it by its index:
my_list = ['1.1', '2.2', '3.3']
result = float(my_list[0]) # Access the first element
print(result) # Output: 1.1
Solution: Convert All List Elements (List Comprehension or map())
To convert all string elements in a list to floats, use a list comprehension or map():
my_list = ['1.1', '2.2', '3.3']
# Using List Comprehension (Recommended)
new_list_comp = [float(x) for x in my_list]
print(new_list_comp) # Output: [1.1, 2.2, 3.3]
# Using map()
new_list_map = list(map(float, my_list))
print(new_list_map) # Output: [1.1, 2.2, 3.3]
Handling ... not 'NoneType'
Cause: You passed the special value None to float().
# Error Example:
example = None
result = float(example) # ⛔️ TypeError: ... not 'NoneType'
Common Sources of None:
- Functions that don't have an explicit
returnstatement (implicitly returnNone). - Variables explicitly set to
None. - Results from methods that modify objects in-place (like
list.sort()).
Solution: Provide a Default Value
Use the or operator to provide a fallback value (like 0 or '0.0') if the variable might be None:
example = None
result = float(example or 0) # If example is None (falsy), use 0
print(result) # Output: 0.0
Solution: Check for None Before Converting
Use an if statement to explicitly check for None:
example = None
result = None # Initialize result
if example is not None:
result = float(example)
else:
print('Variable is None, can not convert.')
result = 0.0 # Assign a default if needed
print(result) # Output: 0.0