0

Say I have two lists with 100,000 elements each and I want to find the set difference but keep the order of the elements. Example:

A = [10, 1, 30, 4, 5, 6]
B = [4, 1, 100]

desired output:

AB = [10, 30, 5, 6]

set(A).difference(set(B)) is producing [10, 5, 6, 30] (notice how it doesn't preserve the order in A) and list comprehension is taking some time (I think it's because of the in operator).

  • Does this help : [link](https://stackoverflow.com/questions/3462143/get-difference-between-two-lists) answered by @markbyers – XXDIL Jan 07 '21 at 07:08

2 Answers2

0

Once you got the set difference, you can compare it with the original list order wise, and then save the result accordingly

A = [10, 1, 30, 4, 5, 6]
B = [4, 1, 100]
C = set(A).difference(set(B))
result = [item for item in A if item in C]

output

[10, 30, 5, 6]  
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

Use list comprehensions

A = [x for x in A if x not in B]