-2

I have the following 2 lists, and I want to obtain the elements of list2 that are not in list1:

list1 = ["0100","0300","0500"]
list2 = ["0100","0200","0300","0400","0500"]

My output should be:

list3 = ["0200","0400"]

I was checking for a way to subtract one from the other, but so far I can't be able to get the list 3 as I want

orestisf
  • 1,396
  • 1
  • 15
  • 30

5 Answers5

2
list3 = [x for x in list2 if x not in list1]

Or, if you don't care about order, you can convert the lists to sets:

set(list2) - set(list1)

Then, you can also convert this back to a list:

list3 = list(set(list2) - set(list1))
orestisf
  • 1,396
  • 1
  • 15
  • 30
1

could this solution work for you?

list3 = []
for i in range(len(list2)):
    if list2[i] not in list1:
        list3.append(list2[i])
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
user6235442
  • 136
  • 7
1
list1 = ["0100","0300","0500"]
list2 = ["0100","0200","0300","0400","0500"]

list3 = list(filter(lambda e: e not in list1,list2))
print(list3)
bp7070
  • 312
  • 2
  • 7
0

I believe this has been answered here:

Python find elements in one list that are not in the other

import numpy as np

list1 = ["0100","0300","0500"]
list2 = ["0100","0200","0300","0400","0500"]

list3 = np.setdiff1d(list2,list1)

print(list3)
0

set functions will help you to solve your problem in few lines of code...

set1=set(["0100","0300","0500"])
set2=set(["0100","0200","0300","0400","0500"])
set3=set2-set1
print(list(set3))

set gives you faster implementation in Python than the Lists...............

Srikeshram
  • 87
  • 1
  • 5