The restore() function of difflib Python module

Overview:

  • Given the differences found between two lists of strings which are generated using the using the difflib.ndiff() function or the compare() method of difflib.Differ() class, the restore() function recreates the input lists.

Example:

# Example Python program that creates 
# the original lists of strings from the differences 
# generated from the ndiff() function. To create the 
# original strings the program uses the restore() method.

import difflib

# String lists
strings1 = ["Square", "Rectangle", "Triangle"]
strings2 = ["Square", "Rectangle", "Angle"]

# Find differences
diffs = difflib.ndiff(strings1, strings2)
diffsList = list(diffs)

print("Differences:")
for diff in diffsList:
    print(diff)

# Get the first list of strings back 
# reconstructed using restore()
recon1 = difflib.restore(diffsList, 1)
print("First list of strings:")
for entry in recon1:
    print(entry)

# Get the second list of strings back 
# reconstructed using restore()
recon2 = difflib.restore(diffsList, 2)
print("Second list of strings:")
for entry in recon2:
    print(entry)

Output:

Differences:
  Square
  Rectangle
- Triangle
+ Angle
First list of strings:
Square
Rectangle
Triangle
Second list of strings:
Square
Rectangle
Angle

 


Copyright 2026 © pythontic.com