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
forloops, with theinoperator, 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
forloop: 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
try:
print("Attempting for loop:")
for digit in number: # can not iterate over 4.75
print(digit)
except TypeError as e:
print(e)try:
print("Attempting list() constructor:")
items = list(number)
print(items)
except TypeError as e:
print(e)try:
print("Attempting sum() function:")
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
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.75to4.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:
calculation = 5 / 2 # Result is 2.5 (float)
for item in calculation: # ⛔️ Error!
...Correct Example:
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}")
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}")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:
for item in data:
print(f" Item: {item}")
print("Iteration successful.")
except TypeError:
print(f"Data (type: {type(data)}) is not iterable. Skipping iteration.")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
try:
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:
sensor_reading = get_reading() # Might return a float like 3.14
if 'error_code' in sensor_reading: # ⛔️ Error if reading is float
...Correct Example:
sensor_reading = 3.14 # Example float reading
valid_codes = ['OK', 'WARN', 'ERROR'] # The iterable to check against
current_status = 'OK'
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.")
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 executedOutput:
'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'
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 executedOutput:
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
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):
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 / 2is5.0). Use integer division//if you need an integer result (10 // 2is5). - 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]) # TrueOutput:
3.14 (type: <class 'float'>) is iterable? False
'text' (type: <class 'str'>) is iterable? True
[1, 2] (type: <class 'list'>) is iterable? TrueConclusion
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 aforloop or with theinoperator if its type might vary.
Do not attempt to iterate directly over floats or use them as the container in membership tests.