The ndiff() function of the Python difflib module

The ndiff() function returns the differences between two lists of strings. The symbols -, + is used to indicate the presence of a string only in the first list and in the second list.

Difflib Module Updated 5 Apr 2026 1 min read

Overview

  • The ndiff() function of Python difflib module returns a generator object containing differences between two lists of strings.
  • Each difference is listed in the format <opcode, string>.
  • When the opcode is '- ' the string is present only in the first list of strings and when it is '+ ' the string is present only in the second list of strings.
  • If the opcode is ' ' there is no difference between the strings. The opcode '? ' represents the intra-line difference between two strings.
  • The output of ndiff() is somewhat like the output of unified_diff() but more compact than that. There are no hunks and line numbers in the ndiff() output.

Example

python
# Example Python program that finds the difference

            # between two lists of strings using the ndiff() function

            # of difflib module

            import difflib

# Create two lists of strings

            textStrings1 = ["Hello", "World"]

            textStrings2 = ["Hello", "Friends"]

# Find the differences

            diffs = difflib.ndiff(textStrings1, textStrings2)

print(diffs)

            print(type(diffs))

            # Print each difference

            for diff in diffs:

                print(diff)

Output

Output
<generator object Differ.compare at 0x102f84cc0>

            <class 'generator'>

              Hello

            - World

            + Friends