list_b
is not necessarily a subset of the data that is contained entirely within list_a
. Consider two much smaller lists with similar make ups.
list_a = [1, 2, 4, 4, 6]
list_b = [1, 3, 4]
As you can see, list_b
contains 3
which is not in list_a
, but the length of list_a
is still greater.
Simple Loop
If you are attempting to get the values that are in list_a
and not in list_b
, the following is a pretty direct translation in Python. Let's convert list_b
to a set so we can get a constant time lookup for element containment.
list_a = [1, 2, 4, 4, 6]
list_b = [1, 3, 4]
set_b = set(list_b)
list_result = []
for a_ele in list_a:
if a_ele not in set_b:
list_result.append(a_ele)
print(list_result)
# [2, 6]
Note: If you do not want duplicate values in your result list, you could simply iterate over set(list_a)
instead of list_a
in the for loop.
Set Logic
You were right to think of using set logic to answer this, which can be accomplished basically as you've written.
set_a = set(list_a)
set_b = set(list_b)
list_result = list(set_a - set_b)
print(list_result)
# [2, 6]
This will create a list that has all of the elements in list_a
with the elements in list_b
removed.