Reputation: 701
I have to find the difference between a list with another list.
But this process of finding the difference totally randomizes my output every time I run.
Below is my script
getALL = ["apple","ball","cat","dog","eagle"] // initial list
Sourcee = ["eagle", "ball"]
diff = list(set(getALL) - set(Sourcee))
for items in diff:
print(items)
Is there any way to keep the sequence of the the diff
list same as getALL
?
I want my output like this:
apple
cat
dog
Upvotes: 3
Views: 185
Reputation: 12015
Just a list comprehension would work. Optionally converting Sourcee
to a set
would make it faster
>>> source_set = set(Sourcee)
>>> [e for e in getALL if e not in source_set]
['apple', 'cat', 'dog']
Upvotes: 5
Reputation: 3930
The set operation does not preserve order. However what you can do is to re-build the diff list, by checking what the order was in the original list. This works for any arbitrary order. If the original list contains duplicates this complicates matters.
getALL = ["apple","ball","cat","dog","eagle"] # initial list
Sourcee = ["eagle", "ball"]
diff = list(set(getALL) - set(Sourcee))
original_order_diff = [x for x in getALL if x in diff]
print(original_order_diff)
Upvotes: 3
Reputation: 71570
Use sorted
:
diff = list(set(getALL) - set(Source))
for items in sorted(diff, key=getALL.index):
print(items)
Even tho:
print('\n'.join([i for i in getALL if i not in Source]))
And:
print(*[i for i in getALL if i not in Source], sep='\n')
Would be the shortest solutions.
They all output:
apple
cat
dog
Upvotes: 2