Python list a collection of data that is used to store multiple values of different data types under a single variable. In this article, I have shared some easiest methods to search substrings in list Python.
Method 1: Using in Operator
This method will print the item of the list if the element contains the substring that we are looking for.
Example
1 2 3 4 5 6 7 8 |
languages = ['java', 'python', 'c++', 'ruby'] substring = 'py' for language in languages: if substring in language: print(language) # python |
We can also get the index of the matched item using the built-in Python index() method.
Example
1 2 3 4 5 6 7 8 9 |
languages = ['java', 'python', 'c++', 'ruby'] substring = 'va' for language in languages: if substring in language: print(f'index of the matched item => {languages.index(language)}') print(f'matched item => {language}') |
Output
1 2 3 4 |
index of the matched item => 0 matched item => java |
Method 2: Using next() method
Python has the built-in method to traverse the list and return the first valid item. In this example, we will search for the first item in the Python list that contains the substring. This method is very useful if you only need the first matching item from the list.
Example
1 2 3 4 5 6 7 |
languages = ['java', 'python', 'c++', 'ruby'] substring = 'y' matched_item = next((language for language in languages if substring in language), None) print(f'index of the matched item => {languages.index(matched_item)}') print(f'matched item => {matched_item}') |
Output
1 2 3 4 |
index of the matched item => 1 matched item => python |
Method 3: Using Lambda
This method is used to find all the matching elements from the Python list that contain the substring.
Example
1 2 3 4 5 6 |
languages = ['java', 'python', 'c++', 'ruby'] substring = 'y' for language in filter(lambda item: substring in item, languages): print(language) |
Output
1 2 3 4 |
python ruby |
Method 4: Using Regex
If you would like to filter the list items by comparing them with the complex string patterns, Python’s re module can be used to find all the matching elements.
Example
1 2 3 4 5 6 7 8 9 |
import re languages = ['java', 'python', 'c++', 'ruby', 'javascript'] substring = 'java' new_list = [language for language in languages if re.search(substring, language)] for item in new_list: print(item) |
Output
1 2 3 4 |
java javascript |