Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: argument of type 'builtin_function_or_method' is not
iterable" occurs when we use the in
or not in
operators with a built-in
function but forget to call it. To solve the error, make sure to call the
built-in function, e.g. my_dict.keys()
.
Here is an example of how the error occurs.
my_dict = {'id': 1, 'name': 'Alice'} # ⛔️ TypeError: argument of type 'builtin_function_or_method' is not iterable print('id' in my_dict.keys) # 👈️ forgot to call function
my_dict.keys()
, so our code actually tries to check for membership in the function rather than in the dict-keys object.To solve the error, make sure to call the built-in function.
my_dict = {'id': 1, 'name': 'Alice'} print('id' in my_dict.keys()) # 👉️ True
We used parenthesis to invoke the built-in function, so now we check for membership in the iterable rather than the function.
Here is another example of how the error occurs when using the str.split()
method.
my_str = 'a,b,c' # ⛔️ TypeError: argument of type 'builtin_function_or_method' is not iterable print('a' in my_str.split) # 👈️ forgot to call function
We forgot to call the method which caused the error.
my_str = 'a,b,c' print('a' in my_str.split(',')) # 👉️ True my_other_str = 'HELLO WORLD' print('hello' in my_other_str.lower()) # 👉️ True
Adding parenthesis to call the method resolves the issue.
The
in 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.