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']
2
  • 2
    Do you want to remove those elements from the existing list, or create a new, filtered list? Commented Jun 25, 2020 at 9:46
  • 1
    stackoverflow.com/questions/3462143/… Commented Jun 25, 2020 at 9:51

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

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.
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])

1 Comment

Note, this works, but is inefficient.
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']

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.