Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Mitran Ana Maria
The Python "TypeError: argument of type 'float' is not iterable" occurs when
we use the membership test operators (in and not in) with a float value. To
solve the error, correct the assignment or convert the float to a string, e.g.
str(my_float)
.
Here is an example of how the error occurs.
my_list = 3.5 # ⛔️ TypeError: argument of type 'float' is not iterable print('a' in my_list)
We tried to use a membership test operator with a float value and got the error.
Chances are you meant to use the operator with an iterable, e.g. a string or a list.
One way to solve the error is to convert the float to a string.
my_str = 3.5 print('a' in str(my_str)) # 👉️ False print('3' in str(my_str)) # 👉️ True
Strings are iterable, so converting the floating-point number to a string solves the issue.
For example, you can reassign the variable if it stores a value of an unexpected type.
my_list = 3.5 if not isinstance(my_list, list): my_list = [] print('a' in my_list) # 👉️ False
We check if the my_list
variable doesn't store a list, and if it doesn't, we
set it to an empty list before using the in
operator.
You can use this approach with any other object, e.g. str
, dict
, tuple
,
etc.
Alternatively, you can check if the value is not a float before using the in
or not in
operators.
my_str = 3.5 if not isinstance(my_str, float): print('a' in my_str) else: # 👇️ this runs print('value is a float')
We check if the value is not an instance of the float
class, and if it isn't,
we use the in
operator to test for membership.
However, it's safer to check if the value is of the expected type, e.g. a str
,
a list
, or a dict
.
my_str = 3.5 if isinstance(my_str, str): print('a' in my_str) else: # 👉️ this runs print('value is not a string')
Our if
statement checks if the value is an instance of the str
class and if
it is, we use the in
operator.
The
in operator
operator tests for membership. For example, x in s
evaluates to True
if x
is a member of s
, otherwise it evaluates to False
.
my_str = 'hello world' print('world' in my_str) # 👉️ True print('another' in my_str) # 👉️ False
x
not in s
returns the negation of x
in s
.
All built-in sequences and set types support the in
and not in
operators.
When used with a dictionary, the operators check for the existence of the
specified key in the dict
object.