In Python, you can Filter a list of strings using another list as conditional data. The list of strings can be filtered without using any method.
Examples filter list of strings in Python
Simple example code.
Filter a list of strings using another list
Get the new list based on match the first word of each value of list2 with the values of list1 and print those values that don’t exist in list1.
Another example using custom function
The custom filter function will find out the common values of both string lists.
list1 = ["A", "B", "C"] list2 = ["D", "A", "C"] def filter_fun(list1, list2): return [n for n in list1 if any(m in n for m in list2)] print(filter_fun(list1, list2))
Output: [‘A’, ‘C’]
Using regular expression to filter list of strings
‘^‘ symbol is used in regular expression patterns to search at the starting of the text.
import re list1 = ["ABC", "BBB", "CDD", "ADD"] def filter_fun(list1): # Search data based on regular expression in the list return [val for val in list1 if re.search(r'^A', val)] print(filter_fun(list1))
Output: [‘ABC’, ‘ADD’]
Using lambda expression to Filter a list of string
lambda expression will omit those values.
w = ["Python", "Code", "Programming"] text = "Learn Python Programming" text_word = text.split() # Using lambda expression filter the data res = ' '.join((filter(lambda val: val not in w, text_word))) print(res)
Use filter() method Python filter list of strings
All values without false will be retrieved from the list as filtered data.
# Declare a list of mix data listData = ['A', 200, 1, 'B', False, True, '0'] filteredData = filter(None, listData) for val in filteredData: print(val, end=' ')
Output: A 200 1 B True 0
Do comment if you have any doubts and suggestions on this Python list tutorial.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.