Reputation: 914
I want to make a list comprehension that iterates through a list of strings, and only gives me back strings which are not present in another predefined list.
samples= ['abc', 'cab', 'bth', 'doc', 'bue']
unwanted= ['doc', 'bue']
wanted_samples= [sample for sample in samples if sample #checks if sample is present in unwanted list]
I have tried to set this up in a couple ways, but it has not worked yet. Any help would be great. It seems like something I should have figured out a while ago, but my brain has just not been cooperating with me today.
Upvotes: 0
Views: 33
Reputation: 1319
You can achieve that by doing this
wanted_samples = [sample for sample in samples if sample not in unwanted]
if the sample is present in the unwanted list, the sample will not be added to wanted_samples
Upvotes: 1
Reputation: 21
You can use not in operator
wanted_samples = [sample for sample in samples if sample not in unwanted]
Upvotes: 1
Reputation: 16526
use not in
:
wanted_samples = [sample for sample in samples if sample not in unwanted]
if it's a sample and your unwanted
list has a lot of words, I suggest using set instead(unwanted= {'doc', 'bue', ...}
). Time Complexity of membership testing for set is O(1).
Upvotes: 1