Check if Any element in List is in String in Python

This tutorial will discuss about a unique way to check if any element in list is in string in Python.

To check if a String contains any value from the list, iterate over all the string elements of list inside any() method.

During iteration, for each string element check if it is present in this given string or not. If yes then it will evaluate to True, otherwise False. This for loop will give a sequence of boolean values, where each True value denotes that the corresponding value of List is present in the given string.

All these boolean values will be passed into the any() method. It will return True, if this sequence has any True value, it means any string element from the list is present in the given string value.

Let’s see the complete example,

# A list of strings
listObj = ["why", "what", "how", "is", "the"]

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

# Check if string has any element from List of strings
if any(elem in strValue for elem in listObj):
    print("Yes, At least one element from List is present in the given string")
else:
    print("No string from list exists in the given string")

Output

Yes, At least one element from List is present in the given string

Summary

We learned how to check if any element of List is present in String 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