Python filter list of strings | Example code

  • by

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 matching the first word of each value of list2 with the values of list1 and print those values that don’t exist in list1.

list1 = ['Python', 'Java', 'JavaScript']
list2 = ['JavaScript is client-side scripting language',
         'PHP is a server-side scripting language',
         'Java is a programming language',
         'Bash is a scripting language']

# Filter the second list based on first list
filter_data = [x for x in list2 if
               all(y not in x for y in list1)]

# Print filter list


Python filter list of strings

Another example using a 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 a list of strings

For this example, you have to import the re module. A regular expression is used to filter those subject codes that start with the word.

‘^‘ symbol is used in regular expression patterns to search at the start 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'^A', val)]


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)))


Output: Learn

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 or suggestions on this Python list tutorial.

Note: IDE: PyCharm 2021.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.

Leave a Reply

Your email address will not be published.

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