0

I have two lists

list1=['value1', 'value2', 'value3']
list2=['value1', 'value2', 'value3', 'value4', 'value5']

I want to delete the contents of list1 from list2

Result should be :

['value4', 'value5']
Anshika Singh
  • 994
  • 12
  • 20
Karsten
  • 35
  • 5

4 Answers4

3

You can do it by converting the list1 to set and then by list comprehension create a new list with the items from list2 that not in list1

list1=['value1', 'value2', 'value3']
list2=['value1', 'value2', 'value3', 'value4', 'value5']
list1_set = set(list1)
result = [i for i in list2 if i not in list1_set]
print(result)

Output

['value4', 'value5']

The conversion of list1 to set is from better performances since checking if an item is in a set is faster than in a list.

Leo Arad
  • 4,452
  • 2
  • 6
  • 17
2

list2 = [elem for elem in list2 if elem not in list1]

Bram Dekker
  • 631
  • 1
  • 7
  • 19
  • Technically, this does not _remove_ from `list2` but overwrite the variable with a new list. You could e.g. use `list[:] = ...` to replace all elements in `list2`. Also, converting `list1` to `set` might be faster. – tobias_k Jun 25 '20 at 09:49
1

To print the values of items in list2 that are not in list1, you can use this code:

list1=['value1', 'value2', 'value3']
list2=['value1', 'value2', 'value3', 'value4', 'value5']

print([list2 for list2 in list2 if list2 not in list1])
Gavin Wong
  • 1,254
  • 1
  • 6
  • 15
1
list1=['value1', 'value2', 'value3']
list2=['value1', 'value2', 'value3', 'value4', 'value5']

set_list_1 = set(list1)
set_list_2 = set(list2)
print(list(set_list_2.difference(set_list_1)))
['value4', 'value5']
SABRIO
  • 11
  • 2