The ndiff() function of the Python difflib module

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 string and when it is '+ ' the string is present only in the second string.
  • If the opcode is '  ' there is no difference between the strings. The opcode '? ' represents the intra-line difference between two strings.

Example:

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

<generator object Differ.compare at 0x102f84cc0>
<class 'generator'>
  Hello
- World
+ Friends

 


Copyright 2026 © pythontic.com