TypeError: 'in <string>' requires string as left operand, not list

avatar

Borislav Hadzhiev

Last updated: Jul 13, 2022

banner

Check out my new book

TypeError: 'in <string>' requires string as left operand, not list #

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.

main.py
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.

main.py
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.

main.py
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.

main.py
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.

All built-in sequences and set types support the 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.

main.py
my_list = [['alice'], ['bob'], ['carl']] print(['bob'] in my_list) # 👉️ True print(['alice'] in my_list) # 👉️ True print(['james'] in my_list) # 👉️ False
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.