Check if All Elements of List are in a String in Python

This tutorial will discuss about a unique way to check if all elements of list are in a string in Python.

Suppose we have a list of strings and a string value i.e.

listObj = ["sample", "is", "text"]

strValue = "This is a sample text message"

Now, we want to check if all the string elements from the list listObj are present in the string strValue or not.

Iterate over all string elements in the list and for each string element check if it is present in the string strValue. During iteration, create a list of boolean values, where each True value represent that the corresponding element of list is present in the string strValue.

Pass this boolean sequence into the all() method. It will return True, if all the values in this boolean sequence are True, it means if all the strings of the list are present in the string strValue.

Let’s see the complete example,

# A List of Strings
listObj = ["sample", "is", "text"]

# A String value
strValue = "This is a sample text message"

# Check if all strings from list exists in a string value
result = all(elem in strValue for elem in listObj)

if result:
    print("Yes, all elements in the list are present in the given string")
else:
    print("No, all elements in the list are not present in the given string")

Output

Yes, all elements in the list are present in the given string

Summary

We learned how to check if a string contains all the elements from list in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top