The restore() function of difflib Python module

The restore() functions recreates the lists of original strings between which the differences were found using the difflib.ndiff() function and the compare() method of the difflib.Differ() class.

Difflib Module Updated 5 Apr 2026 1 min read

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

python
# 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

Output
Differences:

              Square

              Rectangle

            - Triangle

            + Angle

            First list of strings:

            Square

            Rectangle

            Triangle

            Second list of strings:

            Square

            Rectangle

            Angle