Python, remove all occurrences of string in list

Question:

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?

Asked By: Theadamlt

||

Answers:

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'])
Answered By: fraxel
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))
Answered By: ThiefMaster
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'])
Answered By: FallenAngel
l = [u'SQOOP', u'SOLR', u'SLIDER', u'SFTP', u'PIG', u'NODEMANAGER', u'JSQSH', u'HCAT', u'HBASE_REGIONSERVER', u'GANGLIA_MONITOR', u'FLUME_HANDLER', u'DATANODE', u'BIGSQL_WORKER']

p = [u'SQOOP', u'SOLR', u'SLIDER', u'SFTP']

l = [i for i in l if i not in [j for j in p]]

print l
[u'PIG', u'NODEMANAGER', u'JSQSH', u'HCAT', u'HBASE_REGIONSERVER', u'GANGLIA_MONITOR', u'FLUME_HANDLER', u'DATANODE', u'BIGSQL_WORKER']
Answered By: Santhosh Balasa
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.