Python - Test if string contains element from list
Last Updated :
08 Jan, 2025
Improve
Testing if string contains an element from list is checking whether any of the individual items in a list appear within a given string.
Using any() with a generator expression
any() is the most efficient way to check if any element from the list is present in the list.
s = "Python is powerful and versatile."
el = ["powerful", "versatile", "fast"]
# Check if any element in the list exists in the string
# using any() and a generator expression
res = any(elem in s for elem in el)
print(res)
Output
True
Explanation:
- The any() function evaluates if at least one element in the generator expression is True.
- The generator expression iterates through the list and checks each element’s presence in the string using the 'in' operator.
- This approach is efficient as it short-circuits and stops processing once a match is found.
Let's explore some more methods to check how we can test if string contains elements from a list.
Table of Content
Using a for loop
This approach explicitly iterates through the list using a for loop to check for the presence of elements in the string.
s = "Python is powerful and versatile."
el = ["powerful", "versatile", "fast"]
# Initialize the result variable to False
res = False
# Iterate through each element in the list
for elem in el:
if elem in s:
res = True
break
print(res)
Output
True
Explanation:
- The loop iterates through each element in the list 'el' and checks if it exists in the string 's' using the 'in' operator.
- If a match is found, the loop exits early using break, which saves unnecessary iterations.
Using set intersection
Using set intersection method is effective when both the string and the list of elements are relatively short.
s = "Python is powerful and versatile."
el = ["powerful", "versatile", "fast"]
# Split the string into individual words using the split() method'
res = bool(set(s.split()) & set(el))
print(res)
Output
True
Explanation:
- The split() method breaks the string into individual words and sets are created from the string and list elements.
- The & operator computes the intersection of the two sets to check for common elements.
Using regular expressions
Regular expressions provide flexibility for more complex matching scenarios but are less efficient for simple tasks.
import re
s = "Python is powerful and versatile."
el = ["powerful", "versatile", "fast"]
# Compile a regular expression pattern to search for any of the elements in the list
pattern = re.compile('|'.join(map(re.escape, el)))
res = bool(pattern.search(s))
print(res)
Output
True
Explanation:
- The join() method creates a single pattern from the list of elements, separated by | (logical OR).
- The re.compile() function compiles the pattern for faster matching and search checks for its presence in the string.
- This method is less efficient for simple substring checks due to overhead from compiling patterns.