How to filter list items based on regex in python?

Viewed 30

I have two list items and I want to generate a list based on non-matching items. Here is what I am trying to do:

from __future__ import print_function
import os

mainline_list = ['one', 'two', 'three', 'four']
non_main_list = ['two', 'seven', 'six', 'four', 'four-3.1', 'new_three']
itemized_list = [item for item in non_main_list if item not in mainline_list]
print(itemized_list)

What is returns is

['seven', 'six', 'four-3.1', 'new_three']

while what I want is:

 ['seven', 'six']
1 Answers

Regex is not necessary, you can use all() builtin function:

mainline_list = ['one', 'two', 'three', 'four']
non_main_list = ['two', 'seven', 'six', 'four', 'four-3.1', 'new_three']

print([item for item in non_main_list if all(i not in item for i in mainline_list)])

Prints:

['seven', 'six']
Related