Are you comparing an old list with a new list to find out which elements are removed in the new list? After reading this, you know how to use Python List Comprehension to get the items you are interested in.

What items from one list are not in the other list in Python?

The following example creates two lists. The old list has items 1, 2, 3 and 4 and the new list only has items 1 and 2. You might state that the new list is the old list but with items 3 and 4 removed (or deleted). Here is a code example how to find out the deleted items.

Deleted items

old_list = [1, 2, 3, 4]  # 1, 2, 3, 4
new_list = [1, 2, 5]     # 1, 2, 5
deleted = [x for x in old_list if x not in new_list]  # 3, 4
print(deleted)

output:

[3, 4]

You can use this as part of a diffing mechanism. To find out what what elements are added in the new list compared to the old list, you can you this code:

Added items

old_list = [1, 2, 3, 4]  # 1, 2, 3, 4
new_list = [1, 2, 5]     # 1, 2, 5
added = [x for x in new_list if x not in old_list]  # 5
print(added)

output:

[5]

I hope this helps you to use list comprehension to compare lists in Python.

Written by Loek van den Ouweland on 2019-12-27.
Questions regarding this artice? You can send them to the address below.