How to Resolve Python "TypeError: 'float' object is not iterable" and "TypeError: argument of type 'float' is not iterable"
Python's floating-point numbers (float
) represent numerical values, often with decimal components. They are scalar values, not sequences or collections. Errors like TypeError: 'float' object is not iterable
or TypeError: argument of type 'float' is not iterable
occur when you attempt to use a float in a context that requires an iterable, i.e. something that can be looped over or checked for membership, like a list, string, or tuple.
This guide explains why floats aren't iterable and provides solutions for common scenarios where these errors arise, such as loops, built-in functions, and membership tests.
Understanding the Error: Iterables vs. Floats
- Iterables: Objects that can yield their items one by one (e.g., lists, tuples, strings, dictionaries, sets, range objects). They can be used in
for
loops, with thein
operator, and with functions likelist()
,tuple()
,sum()
,min()
,max()
. - Floats (
float
): Represent floating-point numbers (e.g.,3.14
,-0.5
,1e6
). They are single, atomic numeric values and do not contain multiple internal elements to iterate over.
The TypeError
occurs because you've provided a float
where Python expected an iterable object.
Error 1: TypeError: 'float' object is not iterable
This error typically arises when trying to loop over a float or pass it to functions that require an iterable input.
Cause: Using a Float in a for
loop or with Iterator Functions
for
loop: You can not loop directly "through" a float like3.14
. What would the individual items be?- Iterator Functions/Constructors: Functions like
list()
,tuple()
,set()
,sum()
, etc., need an iterable to create a new collection or calculate a result based on its elements.
number = 4.75 # A float variable
# Error Scenario 1: For loop
try:
# ⛔️ TypeError: 'float' object is not iterable
print("Attempting for loop:")
for digit in number: # can not iterate over 4.75
print(digit)
except TypeError as e:
print(e)
# Error Scenario 2: list() constructor
try:
# ⛔️ TypeError: 'float' object is not iterable
print("Attempting list() constructor:")
items = list(number)
print(items)
except TypeError as e:
print(e)
# Error Scenario 3: sum() function
try:
# ⛔️ TypeError: 'float' object is not iterable
print("Attempting sum() function:")
# sum() expects an iterable of numbers, not a single float
total = sum(number)
print(total)
except TypeError as e:
print(e)
Solution: Iterate Over a range()
(for loop counts)
If you intended the float to represent a count for a loop, convert it to an int
first (which truncates the decimal part) and use the range()
function.
loop_count_float = 4.75
# ✅ Convert float to int and use range()
print(f"Looping int({loop_count_float}) = {int(loop_count_float)} times:")
for i in range(int(loop_count_float)): # range(4) -> 0, 1, 2, 3
print(f" Iteration {i}")
int(loop_count_float)
: Converts4.75
to4
.range(4)
: Creates an iterable sequence0, 1, 2, 3
.
Solution: Ensure the Variable Holds an Iterable (Fix the Source)
This is often the real solution. Find out why the variable contains a float when you expected a list, string, tuple, etc.
- Did a calculation result in a float unexpectedly?
- Did a function return a float instead of a list?
- Was a list/string variable accidentally overwritten with a float?
Example with Problematic Code:
# --- Problematic Code ---
calculation = 5 / 2 # Result is 2.5 (float)
for item in calculation: # ⛔️ Error!
...
Correct Example:
# --- Corrected Logic Example ---
# Maybe you meant to iterate over a list containing the result?
calculation = 5 / 2
data_list = [calculation, calculation * 2, calculation * 3] # Create a list
print(f"Iterating over list containing floats: {data_list}")
for item in data_list: # ✅ Iterate over the list
print(f" Item: {item}")
# Or maybe you expected integer division?
int_calculation = 5 // 2 # Result is 2 (int)
print(f"Iterating based on integer division:")
for i in range(int_calculation): # Use range() if it's a count
print(f" Iteration {i}")
Trace the variable assignment and fix the logic to ensure it holds the intended iterable type before the loop or function call.
Handling the Error with try...except
You can catch the error if iterating is optional or needs special handling for non-iterables.
data = 3.14 # Might sometimes be a list or string
print("Using try...except:")
try:
# Attempt iteration
for item in data:
print(f" Item: {item}")
print("Iteration successful.")
except TypeError:
# ✅ Handle the case where data is not iterable (like a float)
print(f"Data (type: {type(data)}) is not iterable. Skipping iteration.")
# Add alternative logic here if needed
Error 2: TypeError: argument of type 'float' is not iterable
This specific phrasing usually occurs when using the membership test operators (in
or not in
) with a float on the right-hand side.
Cause: Using in
or not in
with a Float on the Right Side
The in
operator checks for membership within a container (an iterable). A float is not a container.
measurement = 98.6
# Error Scenario
try:
# ⛔️ TypeError: argument of type 'float' is not iterable
# can not check if 'some_value' is 'in' 98.6
if 'some_value' in measurement:
print("Value found.")
except TypeError as e:
print(e)
Solution: Ensure the Right-Side Operand is an Iterable
Fix the logic so the variable on the right side of in
holds the intended list, string, tuple, set, or dictionary keys you want to search within.
Example with Problematic Code:
# --- Problematic Code ---
sensor_reading = get_reading() # Might return a float like 3.14
if 'error_code' in sensor_reading: # ⛔️ Error if reading is float
...
Correct Example:
# --- Corrected Logic Example ---
sensor_reading = 3.14 # Example float reading
valid_codes = ['OK', 'WARN', 'ERROR'] # The iterable to check against
# Assume we have a status derived elsewhere
current_status = 'OK'
# ✅ Check if current_status is in the list of valid codes
if current_status in valid_codes:
print(f"'{current_status}' is a valid status code.") # This is executed
else:
print(f"'{current_status}' is not a valid status code.")
# Make sure the variable 'sensor_reading' isn't mistakenly used for the container
# Instead, perhaps check the *value* against some range:
if isinstance(sensor_reading, float) and 3.0 < sensor_reading < 4.0:
print(f"Sensor reading {sensor_reading} is in the valid range.") # This is executed
Output:
'OK' is a valid status code.
Sensor reading 3.14 is in the valid range.
Solution: Convert Float to String for Character Search
If you genuinely want to check if a specific character (like the decimal point .
or a digit 3
) exists within the string representation of the float, convert the float to a string first.
number = 3.14159
target_char = '.'
target_digit = '3'
# ✅ Convert float to string before using 'in'
number_str = str(number)
print(f"Number as string: '{number_str}'")
if target_char in number_str:
print(f"Character '{target_char}' found in string representation.") # This is executed
if target_digit in number_str:
print(f"Digit '{target_digit}' found in string representation.") # This is executed
if '9' in number_str:
print(f"Digit '9' found in string representation.") # This is executed
if '7' in number_str:
print(f"Digit '7' found.")
else:
print(f"Digit '7' NOT found in string representation.") # This is executed
Output:
Number as string: '3.14159'
Character '.' found in string representation.
Digit '3' found in string representation.
Digit '9' found in string representation.
Digit '7' NOT found in string representation.
Solution: Check Type Before Using in
/ not in
If a variable might hold different types, check it's an appropriate iterable type before using in
.
data_container = 99.0 # Might be a list, tuple, string, or float
# ✅ Check if it's an iterable type suitable for 'in'
if isinstance(data_container, (list, tuple, str, set, dict)):
if 'target' in data_container:
print("'target' found in iterable.")
else:
print("'target' not found in iterable.")
elif isinstance(data_container, float):
# This block runs
print("Variable holds a float, 'in' check skipped.")
else:
print(f"Variable holds unexpected type: {type(data_container)}")
Output:
Variable holds a float, 'in' check skipped.
Common Sources of Unexpected Float Values
- Division: Standard division
/
always produces a float (e.g.,10 / 2
is5.0
). Use integer division//
if you need an integer result (10 // 2
is5
). - Calculations: Mathematical operations often result in floats.
- Function Returns: Functions reading sensors, performing calculations, or parsing data might return floats.
- Accidental Reassignment: Overwriting a list/string variable with a float.
Checking if an Object is Iterable (General)
Use try...except TypeError
with iter()
to determine if an object supports iteration.
from collections.abc import Iterable # More robust check
def check_iterability_robust(obj):
is_iterable = isinstance(obj, Iterable) # Check using Abstract Base Class
print(f"{repr(obj)} (type: {type(obj)}) is iterable? {is_iterable}")
return is_iterable
check_iterability_robust(3.14) # False
check_iterability_robust("text") # True
check_iterability_robust([1,2]) # True
Output:
3.14 (type: <class 'float'>) is iterable? False
'text' (type: <class 'str'>) is iterable? True
[1, 2] (type: <class 'list'>) is iterable? True
Using isinstance(obj, collections.abc.Iterable)
is often a more direct way to check for general iterability than the try...except iter()
approach.
Conclusion
The TypeError: 'float' object is not iterable
and TypeError: argument of type 'float' is not iterable
errors occur because floats represent single numeric values, not sequences or collections.
To resolve this:
- Ensure the variable holds an iterable: The best fix is often to find why your variable contains a float when you expected a list, string, tuple, etc., and correct that upstream logic.
- Use
range(int(my_float))
: If you intend to loop a number of times represented by the float's integer part. - Convert to
str()
: If you need to check for character membership within the string representation of the float ('.' in str(3.14)
). - Check types: Use
isinstance()
to verify a variable holds an appropriate iterable type before using it in afor
loop or with thein
operator if its type might vary.
Do not attempt to iterate directly over floats or use them as the container in membership tests.