Bootstrap FreeKB - Python (Scripting) - List differences between lists using difflib Differ compare
Python (Scripting) - List differences between lists using difflib Differ compare

Updated:   |  Python (Scripting) articles

The Differ class of the difflib module with the compare filter can be used to list the differences between items in a list. In this example, the "a" list is totally different from the "b" list.

from difflib import Differ

a = ["Hello World"]
b = ["Goodbye World"]
print('\n'.join(Differ().compare(a, b)))

 

Running this script should return the following

  • The - character means the item in list "a" is different from the item in list "b"
  • The + character means the item in list "b" is different from the item in list "a"
- Hello World
+ Goodbye World

 

If there are no differences between the items in the list.

from difflib import Differ

a = ["Hello World"]
b = ["Goodbye World"]
print('\n'.join(Differ().compare(a, b)))

 

Then something like this will be returned, where there are two spaces before the identical lines.

~]$ python testing.py
  Hello World

 

Let's say the items in the lists are similar, but not identical.

from difflib import Differ

a = ["Hello World"]
b = ["Hello x World"]
print('\n'.join(Differ().compare(a, b)))

 

In this scenario, something like this will be returned.

  • The - character means the item in list "a" is different from the item in list "b"
  • The + character means the item in list "b" is different from the item in list "a"
  • The ? character attempts to identify the position of the slight difference
- Hello World
+ Hello x World
?       ++

 

Often, you probably want to compare file "a" to file "b", to determine if the files are identical or if the files contain any differences. The files can be opened using open and then read and split or splitlines to put each line in the file as a unique item in a list.

from difflib import Differ

with open("a.txt", "r") as file:
  a = file.read().splitlines()

with open("b.txt", "r") as file:
  b = file.read().splitlines()

print('\n'.join(Differ().compare(a, b)))

 

Here is how you can loop through the results, line by line.

from difflib import Differ

with open("a.txt", "r") as file:
  a = file.read().splitlines()

with open("b.txt", "r") as file:
  b = file.read().splitlines()

for line in Differ().compare(a, b)):
  print(line)

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 4ccdbc in the box below so that we can be sure you are a human.