Borislav Hadzhiev
Last updated: Jul 13, 2022
Check out my new book
The Python "TypeError: 'in <string>' requires string as left operand, not
list" occurs when we use the in
operator with a left-hand side value of a list
and a right-hand side value of a string. To solve the error, move the list to
the right-hand side of the in
operator.
my_str = 'bob' my_list = ['alice', 'bob', 'carl'] # ⛔️ TypeError: 'in <string>' requires string as left operand, not list result = my_list in my_str
We used the in
operator with a list on the left-hand side and a string on the
right-hand side which caused the error.
To solve the error, move the list to the right-hand side of the in
operator.
my_str = 'bob' my_list = ['alice', 'bob', 'carl'] result = my_str in my_list print(result) # 👉️ True if my_str in my_list: print('string is in list') else: print('string is NOT in list')
The
in operator
tests for membership. For example, x in l
evaluates to True
if x
is a
member of l
, otherwise it evaluates to False
.
my_list = ['alice', 'bob', 'carl'] print('bob' in my_list) # 👉️ True print('james' in my_list) # 👉️ False
If you need to check if a string is NOT in a list, use the not in
operator
instead.
my_list = ['alice', 'bob', 'carl'] print('bob' not in my_list) # 👉️ False print('james' not in my_list) # 👉️ True
x not in l
returns the negation of x in l
.
in
and not in
operators.You can also use this approach to check if a list contains another list, if you have a two-dimensional list.
my_list = [['alice'], ['bob'], ['carl']] print(['bob'] in my_list) # 👉️ True print(['alice'] in my_list) # 👉️ True print(['james'] in my_list) # 👉️ False