Skip to main content

How to Resolve Python "TypeError: 'in <string>' requires string as left operand, not ..." (list, int, dict)

The TypeError: 'in <string>' requires string as left operand, not X (where X is commonly list, int, dict, or another non-string type) is a specific Python error related to the membership test operator (in or not in). It occurs when you try to check if a non-string value (X) is contained within a string on the right side. Python's in operator, when used with a string on the right, expects the item being searched for (the left operand) also to be a string (or a single character).

This guide explains the correct usage of the in operator with strings and provides solutions for this common type mismatch when the left operand is a list, integer, or dictionary.

Understanding the Error: The in Operator with Strings

The in operator in Python performs a membership test. Its behavior depends on the type of the object on the right-hand side:

  • item in sequence (e.g., list, tuple, string): Checks if item exists as an element or substring within the sequence.
  • kepy in mapping (e.g., dictionary): Checks if key exists as a key in the mapping.
  • element in set: Checks if element exists in the set.

When the object on the right side is a string, Python expects the in operator to perform a substring check. For this specific operation (something in my_string), the item being searched for (the left operand, something) must also be a string. You can not directly check if a list, integer, dictionary, or other non-string type is "contained within" a string using in this way.

Cause 1: Left Operand is list

This error occurs if you place a list variable on the left side of in and a string variable on the right.

Error Scenario (list in string)

search_terms = ["error", "warning"]                     # A list
log_message = "An error occurred during processing." # A string

try:
# ⛔️ TypeError: 'in <string>' requires string as left operand, not list
# Trying to check if the list object exists within the string
if search_terms in log_message:
print("Found list in string?") # Logically incorrect for 'in'
except TypeError as e:
print(e)

Solution: Reverse Operands (string in list) or Check List Elements

Your intended logic was likely different:

  • Check if a specific string is an element of the list: Reverse the operands.

    term_to_find = "error"
    list_of_terms = ["error", "warning", "info"]

    # ✅ Check if the string term_to_find is in the list list_of_terms
    if term_to_find in list_of_terms:
    print(f"'{term_to_find}' is present in the list.") # This is executed

    Output:

    'error' is present in the list.
  • Check if any string from the list is a substring of the target string: Iterate through the list.

    search_terms = ["error", "warning"]
    log_message = "An error occurred during processing."

    # ✅ Check if ANY term from the list is a substring of log_message
    found = any(term in log_message for term in search_terms)
    if found:
    print(f"At least one term from {search_terms} was found in '{log_message}'.") # This is executed

    Output:

    At least one term from ['error', 'warning'] was found in 'An error occurred during processing.'.

Cause 2: Left Operand is int (or float)

You cannot directly check for the presence of a numeric type within a string using in.

Error Scenario (int in string)

record_id = 123 # An integer
text_data = "Transaction 12345 completed."

try:
# ⛔️ TypeError: 'in <string>' requires string as left operand, not int
# Trying to find the number 123 within the string text_data
if record_id in text_data:
print("Numeric ID found in text?")
except TypeError as e:
print(e)

Solution: Convert Number to String (str()) Before Check

Convert the number to its string representation before performing the substring check.

record_id = 123
text_data = "Transaction 12345 completed."

# ✅ Convert the number to string '123' before checking
if str(record_id) in text_data:
print(f"String '{str(record_id)}' found in '{text_data}'.") # This is executed
else:
print(f"String '{str(record_id)}' not found in '{text_data}'.")

Cause 3: Left Operand is dict

Attempting my_dict in my_string is syntactically incorrect. The likely intent involves checking for dictionary keys.

Error Scenario (dict in string)

config = {"host": "localhost", "port": 80} # A dictionary
url_options = "host=example.com&port=8080" # A string

try:
# ⛔️ TypeError: 'in <string>' requires string as left operand, not dict
if config in url_options:
print("Config dict found in URL string?")
except TypeError as e:
print(e)

Solution: Reverse Operands for Key Check (key_string in dict)

If you meant to check if a specific key (which is typically a string) exists within the dictionary, put the key string on the left and the dictionary on the right.

config = {"host": "localhost", "port": 80}
key_to_check = "port" # A string

# ✅ Check if the STRING key exists IN the DICTIONARY
if key_to_check in config:
print(f"Key '{key_to_check}' is present in the config dict.") # This is executed
else:
print(f"Key '{key_to_check}' is not in the config dict.")

Output:

Key 'port' is present in the config dict.

Correct Usage Review

Remember the valid uses of in:

  • Substring Check: substring_str in main_str (Both must be strings).
  • List/Tuple/Set Element Check: element in my_list (Checks if element is an item in the list/tuple/set).
  • Dictionary Key Check: key_str in my_dict (Checks if key_str is a key in the dictionary).

The error specifically occurs in the first case (substring check) when the left operand isn't a string.

Debugging the Error (type())

When you encounter TypeError: 'in <string>' requires string as left operand, not X:

  1. Examine the in operation causing the error.
  2. Identify the variable or literal on the left side.
  3. Print its type: print(type(left_operand)). This will confirm it's the type X (e.g., list, int, dict) mentioned in the error message.
  4. Verify the variable on the right side is indeed a string: print(type(right_operand)).
  5. Apply the correct solution based on the types and your intended logic (reverse operands, convert number to string, use any() for list elements, etc.).

Conclusion

The TypeError: 'in <string>' requires string as left operand, not X occurs when the membership operator in is used with a string on the right side, but the value being searched for (on the left side) is not a string (it's type X).

To fix this:

  • If checking for substrings, ensure both operands are strings. Convert numbers to strings using str() first (str(number) in my_string).
  • If checking for element membership in a list, ensure the list is on the right side (element in my_list).
  • If checking for key existence in a dictionary, ensure the dictionary is on the right side (key_string in my_dict).

Understanding the specific behavior of the in operator based on the type of the right-hand operand is crucial for avoiding this TypeError.