Python, remove all occurrences of string in list

list, python, string

Solution

If the order is not important you can use sets:

>>> main_array = ['bacon', 'cheese', 'milk', 'cake', 'tomato']
>>> second_array = ['cheese', 'tomato']
>>> set(main_array) & set(second_array)
set(['tomato', 'cheese'])

Here we use the intersection operator, `&`. Should you only want items not found in your second list, we can use difference, `-`:

>>> set(main_array) - set(second_array)
set(['cake', 'bacon', 'milk'])

Problem

Say i have a list: ``` main_list = ['bacon', 'cheese', 'milk', 'cake', 'tomato'] ``` and another list: ``` second_list = ['cheese', 'tomato'] ``` How can I remove all elements that are found in the second list, from the main list?

Original source

Related problems