Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, remove all occurrences of string in list

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?

like image 814
Theadamlt Avatar asked May 12 '12 11:05

Theadamlt


3 Answers

new_array = [x for x in main_array if x not in second_array]

However, this is not very performant for large lists. You can optimize by using a set for second_array:

second_array = set(second_array)
new_array = [x for x in main_array if x not in second_array]

If the order of the items does not matter, you can use a set for both arrays:

new_array = list(set(main_array) - set(second_array))
like image 89
ThiefMaster Avatar answered Oct 12 '22 00:10

ThiefMaster


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'])
like image 9
fraxel Avatar answered Oct 11 '22 22:10

fraxel


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

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

main_array.intersection(second_array)
>>> set(['cheese', 'tomato'])
like image 3
FallenAngel Avatar answered Oct 11 '22 23:10

FallenAngel