How to check if words from one list is present in an element of another list in Python ?

Introduction

In Python, when working with lists of strings, you may encounter situations where you need to determine if certain words are present in one or more elements of another list. Python offers powerful tools like list comprehensions, combined with built-in functions like any() and all(), to accomplish this efficiently.

This article will explore how to use these tools to check for the presence of words in a list of strings, and the difference between using any() and all() to refine your checks.

Using List Comprehension and any()

The any() function allows you to check if at least one condition in an iterable is True. When used in conjunction with list comprehension, it becomes an effective way to check whether any word from one list is present in the elements of another list.. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# List of words to check
words = ["word1", "word2", "word3"]

# List of sentences or strings
elements = ["This is word1 in a sentence", "Another sentence", "No matching words here"]

# Check if any word is in any element of the list
matches = [element for element in elements if any(word in element for word in words)]

print(matches)

Output:

1
['This is word1 in a sentence']

In this example, the code checks if any word from the words list is found in each string from the elements list. If a word is found in the string, that string is added to the matches list. In the output, only the sentence containing "word1" is returned because it's the only match.

Using list comprehension and all()

If you want to check whether all words from one list are present in an element of another list, you can modify the code to use all() instead of any(). This will ensure that the element contains all words from the list.

Here's how you can do it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# List of words to check
words = ["word1", "word2", "word3"]

# List of sentences or strings
elements = ["This is word1 and word2 in a sentence", 
            "This sentence contains word1, word2, and word3", 
            "This only has word1"]

# Check if all words are in any element of the list
matches = [element for element in elements if all(word in element for word in words)]

print(matches)

Output:

1
['This sentence contains word1, word2, and word3']

In this version, the code checks if all words in the words list are present in each string in elements. Only the strings that contain all the words will be included in the matches list.

References

Links Site
any() docs.python.org
all() docs.python.org