3

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
Prashant Kumar
  • 501
  • 8
  • 26
  • 2
    How about a list comprehension: `[i for i in getALL if i not in Source]`? – Chris Jul 26 '19 at 07:26
  • 3
    Possible duplicate of [preserving the order in difference between two lists in python](https://stackoverflow.com/questions/32384312/preserving-the-order-in-difference-between-two-lists-in-python) – Georgy Jul 26 '19 at 08:16

3 Answers3

5

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']
Sunitha
  • 11,777
  • 2
  • 20
  • 23
  • can you please explain this part `[e for e in getALL if e not in source_set]` in simple terms. – Prashant Kumar Jul 26 '19 at 08:28
  • 1
    You are just iterating through the list and grabbing its elements `e` for which the condition `e not in source_set` is True. And the condition would be true only when the element `e` is not present in `source_set` – Sunitha Jul 26 '19 at 08:31
3

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)
Jurgen Strydom
  • 3,540
  • 1
  • 23
  • 30
2

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
U13-Forward
  • 69,221
  • 14
  • 89
  • 114