Skip to main content

How to Check if String Contains Element of a List and if Any Element in a List Contains a String in Python

When working with strings and lists in Python, two common searching tasks arise:

  1. Determining if a primary string contains any of the elements from a given list of potential substrings.
  2. Determining if any of the string elements within a given list contain a specific target substring.

While related, these require slightly different approaches.

This guide demonstrates clear and Pythonic methods using any(), list comprehensions, and loops to solve both scenarios, including case-insensitive checks and retrieving matches.

Scenario 1: Check if String Contains ANY Element from a List

Goal: Given a main string and a list of potential substrings, determine if the main string contains at least one of those substrings.

Example Data:

main_string = "This website is tutorialreference.com"
search_list = ["python", "tutorialreference", ".org"]

This checks efficiently if any element from search_list is present in main_string.

main_string = "This website is tutorialreference.com"
search_list = ["python", "tutorialreference", ".org"]

# ✅ Check if any item in search_list is a substring of main_string
found_any = any(item in main_string for item in search_list)

print(f"String: '{main_string}'")
print(f"Search List: {search_list}")
print(f"String contains any list element? {found_any}") # Output: True ('tutorialreference' is found)

if found_any:
print("--> The string contains at least one element from the list.") # This is executed
else:
print("--> The string does NOT contain any elements from the list.")

Output:

String: 'This website is tutorialreference.com'
Search List: ['python', 'tutorialreference', '.org']
String contains any list element? True
--> The string contains at least one element from the list.
  • (item in main_string for item in search_list): Generates True or False for each item based on whether it's found within main_string.
  • any(...): Returns True as soon as the first True is generated (short-circuits).

Getting the First Matching Element from the List (:=)

To find out which element from the list was found first (requires Python 3.8+).

main_string = "This website is tutorialreference.com"
search_list = ["python", "tutorialreference", ".org"]
first_found_item = None

# ✅ Use assignment expression inside any()
if any((match := item) in main_string for item in search_list):
print("String contains at least one element!")
# 'match' holds the first item from search_list found in main_string
first_found_item = match
print(f"The first matching item found was: '{first_found_item}'") # Output: 'tutorialreference'
else:
print("String does not contain any elements from the list.")

print(f"Final value of first_found_item: {first_found_item}") # Output: 'tutorialreference'

Output:

String contains at least one element!
The first matching item found was: 'tutorialreference'
Final value of first_found_item: tutorialreference

Getting ALL Matching Elements from the List

Use a list comprehension or filter to get all elements from search_list that are present in main_string.

main_string = "This website is tutorialreference.com"
search_list = ["python", "tutorialreference", ".com", "site"]

# ✅ Use list comprehension
all_found_items = [item for item in search_list if item in main_string]
print(f"All list elements found in string: {all_found_items}")
# Output: All list elements found in string: ['tutorialreference', '.com', 'site']

# Alternative using filter
# all_found_items_filter = list(filter(lambda item: item in main_string, search_list))
# print(f"All found (filter): {all_found_items_filter}")

Case-Insensitive Check

Convert both the main string and each list element to the same case before comparison.

main_string_case = "Apple BANANA Cherry"
search_list_case = ["banana", "grape", "CHERRY"]

# ✅ Convert both to lowercase (or .casefold())
found_any_insensitive = any(item.lower() in main_string_case.lower()
for item in search_list_case)

print(f"String: '{main_string_case}'")
print(f"Search List: {search_list_case}")
print(f"Any found (insensitive)? {found_any_insensitive}") # Output: True ('banana' and 'CHERRY' match)

Output:

String: 'Apple BANANA Cherry'
Search List: ['banana', 'grape', 'CHERRY']
Any found (insensitive)? True

Using a for Loop Alternative

More explicit, but less concise.

main_string = "This website is tutorialreference.com"
search_list = ["python", "tutorialreference", ".org"]
found_one_loop = False

print("Checking with loop (Scenario 1):")
for item in search_list:
print(f"Checking for '{item}'...")
if item in main_string:
print(f"--> Found '{item}'!")
found_one_loop = True
break # Stop searching

if found_one_loop:
print("Result: String contains at least one list element.") # This runs
else:
print("Result: String contains none of the list elements.")

Output:

Checking with loop (Scenario 1):
Checking for 'python'...
Checking for 'tutorialreference'...
--> Found 'tutorialreference'!
Result: String contains at least one list element.

Scenario 2: Check if ANY Element in a List Contains a String

Goal: Given a list of strings and a specific target substring, determine if any of the strings in the list contain that target substring.

Example Data:

list_to_search = ["apple pie", "banana bread", "cherry cake"]
target_substring = "banana"

This checks if the target_substring is found within any of the strings in list_to_search.

list_to_search = ["apple pie", "banana bread", "cherry cake"]
target_substring = "banana"
substring_not_present = "kiwi"

# ✅ Check if target_substring is in any element of list_to_search
found_in_any_element = any(target_substring in element for element in list_to_search)

print(f"List: {list_to_search}")
print(f"Target Substring: '{target_substring}'")
print(f"Substring found in any list element? {found_in_any_element}") # Output: True

if found_in_any_element:
print("--> Substring found in at least one list element.") # This is executed
else:
print("--> Substring not found in any list element.")


# Example with no matches
found_in_any_none = any(substring_not_present in element for element in list_to_search)
print(f"Substring '{substring_not_present}' found in any list element? {found_in_any_none}") # Output: False

Output:

List: ['apple pie', 'banana bread', 'cherry cake']
Target Substring: 'banana'
Substring found in any list element? True
--> Substring found in at least one list element.
Substring 'kiwi' found in any list element? False
  • (target_substring in element for element in list_to_search): Generates True or False for each element based on whether it contains the target_substring.
  • any(...): Returns True if any of the checks yield True.

Case-Insensitive Check

Convert both the target substring and each list element to the same case.

list_mixed_case = ["Apple Pie", "Banana Bread", "Cherry Cake"]
target_substring_lower = "banana"

# ✅ Convert both to lowercase
found_any_insensitive2 = any(target_substring_lower.lower() in element.lower()
for element in list_mixed_case)

print(f"List: {list_mixed_case}")
print(f"Target Substring: '{target_substring_lower}'")
print(f"Found in any (insensitive)? {found_any_insensitive2}") # Output: True

Output:

List: ['Apple Pie', 'Banana Bread', 'Cherry Cake']
Target Substring: 'banana'
Found in any (insensitive)? True

Getting ALL List Elements Containing the String

Use a list comprehension or filter to find all strings from the list that contain the target substring.

list_to_search = ["apple pie", "banana bread", "cherry cake", "banana smoothie"]
target_substring = "banana"

# ✅ Use list comprehension
elements_containing_sub = [element for element in list_to_search
if target_substring in element]
print(f"List elements containing '{target_substring}': {elements_containing_sub}")
# Output: List elements containing 'banana': ['banana bread', 'banana smoothie']

# Alternative using filter
# elements_containing_filter = list(filter(lambda el: target_substring in el, list_to_search))
# print(f"Elements containing (filter): {elements_containing_filter}")

Output:

List elements containing 'banana': ['banana bread', 'banana smoothie']

Using a for Loop Alternative

list_to_search = ["apple pie", "banana bread", "cherry cake"]
target_substring = "banana"
found_in_element_loop = False
element_containing = None

print("Checking with loop (Scenario 2):")
for element in list_to_search:
print(f"Checking element: '{element}'...")
if target_substring in element:
print(f"--> Found '{target_substring}' in '{element}'!")
found_in_element_loop = True
element_containing = element # Store which element had it
break # Stop searching

if found_in_element_loop:
print(f"Result: Substring found in at least one element ('{element_containing}').") # This is executed
else:
print("Result: Substring not found in any element.")

Output:

Checking with loop (Scenario 2):
Checking element: 'apple pie'...
Checking element: 'banana bread'...
--> Found 'banana' in 'banana bread'!
Result: Substring found in at least one element ('banana bread').

Choosing Between any() and Loops

  • any() with Generator Expression: Recommended for simple existence checks in both scenarios. It's concise, efficient (short-circuits), and clearly conveys the intent.
  • List Comprehension / filter(): Use these when you need to collect the items that satisfy the condition (either the matching substrings from the search list, or the list elements containing the target substring).
  • for Loop: Use when the logic inside the loop is more complex than a simple in check, or for maximum clarity in step-by-step execution, or if you need fine-grained control over actions taken when a match is found.

Conclusion

Python provides clear and efficient ways to check for substring relationships between strings and lists:

  • To check if a string contains ANY element from a list: Use any(element in main_string for element in list_of_elements).
  • To check if ANY element in a list contains a string: Use any(substring in element for element in list_of_strings).

Remember to use .lower() or .casefold() on both sides of the in operator for case-insensitive comparisons. Use list comprehensions when you need to identify which items matched, rather than just getting a True/False result.