Use any() function to check if the list contains a substring in Python. Pass iterable in this method as a for-loop that checks if any element in the list contains the substring.
An example of if a list contains the substring in Python
Simple example code check if "wo"
contain in the given list.
sList = ["one", "two", "three"]
sub_str = "wo"
res = any(sub_str in string for string in sList)
print(res)
Output:
![Python if the list contains substring](https://i0.wp.com/tutorial.eyehunts.com/wp-content/uploads/2021/11/Python-if-the-list-contains-substring.jpg?resize=220%2C112&ssl=1)
Another example
Use a list comprehension to construct a new list containing each element that contains the substring.
sList = ["one", "two", "three"]
sub_str = "wo"
res = [string for string in sList if sub_str in string]
print(res)
Output: [‘two’]
Do comment if you have any doubts or suggestions on this Python List code
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Thanks for sharing this Python code snippet! Using the ‘any()’ function and list comprehension makes it easy to check for substrings in a list. It’s a concise solution.