karen iazydjan
karen iazydjan

Reputation: 53

How to filter out list elements that contain invalid characters in Python 3.x?

I am writing a function in Python 3.x that will take a list of string variables and a list of valid characters as arguments and return a filtered list containing elements of original list that are made up of valid characters only. I think I can achieve the result using two nested For loops to iterate through list elements and then go through each character of the given element, but I want to know if there is a more efficient way to get this result using Python methods or functions.

For the following two lists:

valid_characters = ['A','B','C']
my_list = ['abcde','AbCB','ABCBA','XYZ','CBCBB','CABzBAC']

The function would return filtered list ['ABCBA','CBCBB']

Upvotes: 5

Views: 854

Answers (1)

blhsing
blhsing

Reputation: 106881

You can convert valid_characters to a set so that you can efficiently determine if a string is made up purely of characters in the set by testing if the set is a superset of the characters in the string:

valid_set = set(valid_characters)
print([s for s in my_list if valid_set.issuperset(s)])

This outputs:

['ABCBA', 'CBCBB']

Upvotes: 7

Related Questions