Python Test if string contains element from list (original) (raw)
Last Updated : 08 Jan, 2025
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.
Python `
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)
`
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.
Python `
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)
`
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.
Python `
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)
`
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.
Python `
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)
`
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.
Similar Reads
- Python - Check if List contains elements in Range Checking if a list contains elements within a specific range is a common problem. In this article, we will various approaches to test if elements of a list fall within a given range in Python. Let's start with a simple method to Test whether a list contains elements in a range. Using any() Function 3 min read
- Python | Test if any list element returns true for condition Sometimes, while coding in Python, we can have a problem in which we need to filter a list on basis of condition met by any of the element. This can have it's application in web development domain. Let's discuss a shorthand in which this task can be performed. Method : Using any() + list comprehensi 4 min read
- Python - Test if any set element exists in List Given a set and list, the task is to write a python program to check if any set element exists in the list. Examples: Input : test_dict1 = test_set = {6, 4, 2, 7, 9, 1}, test_list = [6, 8, 10] Output : True Explanation : 6 occurs in list from set. Input : test_dict1 = test_set = {16, 4, 2, 7, 9, 1}, 4 min read
- Python - Test if tuple list has Single element Given a Tuple list, check if it is composed of only one element, used multiple times. Input : test_list = [(3, 3, 3), (3, 3), (3, 3, 3), (3, 3)] Output : True Explanation : All elements are equal to 3. Input : test_list = [(3, 3, 3), (3, 3), (3, 4, 3), (3, 3)] Output : False Explanation : All elemen 8 min read
- Python - String concatenation in Heterogeneous list Sometimes, while working with Python, we can come across a problem in which we require to find the concatenation of strings. This problem is easier to solve. But this can get complex cases we have a mixture of data types to go along with it. Let’s discuss certain ways in which this task can be perfo 4 min read
- Python - Check if string starts with any element in list We need to check if a given string starts with any element from a list of substrings. Let's discuss different methods to solve this problem. Using startswith() with tuplestartswith() method in Python can accept a tuple of strings to check if the string starts with any of them. This is one of the mos 3 min read
- Check if any element in list satisfies a condition-Python The task of checking if any element in a list satisfies a condition involves iterating through the list and returning True if at least one element meets the condition otherwise, it returns False. For example, in a = [4, 5, 8, 9, 10, 17], checking ele > 10 returns True as 17 satisfies the conditio 3 min read
- Python - Find Index containing String in List In this article, we will explore how to find the index of a string in a list in Python. It involves identifying the position where a specific string appears within the list. Using index()index() method in Python is used to find the position of a specific string in a list. It returns the index of the 3 min read
- Python | Even Front digits Test in List Sometimes we may face a problem in which we need to find a list if it contains numbers that are even. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. Method #1: Using list comprehension + map() We can approach this pro 5 min read
- Python | Convert string enclosed list to list Given a list enclosed within a string (or quotes), write a Python program to convert the given string to list type. Examples: Input : "[0, 2, 9, 4, 8]" Output : [0, 2, 9, 4, 8] Input : "['x', 'y', 'z']" Output : ['x', 'y', 'z'] Approach #1: Python eval() The eval() method parses the expression passe 5 min read