I'm also still trying to figure out why many difflib functions return a generator instead of a list, what's the advantage there?

Well, think about it for a second - if you compare files, those files can in theory (and will be in practice) be quite large - returning the delta as a list, for exampe, means reading the complete data into memory, which is not a smart thing to do.

As for only returning the difference, well, there is another advantage in using a generator - just iterate over the delta and keep whatever lines you are interested in.

If you read the difflib documentation for Differ - style deltas, you will see a paragraph that reads:

Each line of a Differ delta begins with a two-letter code:
Code    Meaning
'- '    line unique to sequence 1
'+ '    line unique to sequence 2
'  '    line common to both sequences
'? '    line not present in either input sequence

So, if you only want differences, you can easily filter those out by using str.startswith

You can also use difflib.context_diff to obtain a compact delta which shows only the changes.

Answer from Jim Brissom on Stack Overflow
🌐
Beautiful Soup
tedboy.github.io › python_stdlib › generated › generated › difflib.ndiff.html
difflib.ndiff() — Python Standard Library
difflib.ndiff(a, b, linejunk=None, charjunk=<function IS_CHARACTER_JUNK>)[source]¶ · Compare a and b (lists of strings); return a Differ-style delta. Optional keyword parameters linejunk and charjunk are for filter functions (or None): linejunk: A function that should accept a single string argument, and return true iff the string is junk. The default is None, and is recommended; as of Python 2.3, an adaptive notion of “noise” lines is used that does a good job on its own.
🌐
Python
docs.python.org › 3 › library › difflib.html
difflib — Helpers for computing deltas
Given a sequence produced by Differ.compare() or ndiff(), extract lines originating from file 1 or 2 (parameter which), stripping off line prefixes.
🌐
Coderz Column
coderzcolumn.com › tutorials › python › difflib-simple-way-to-find-out-differences-between-sequences-file-contents-using-python
difflib - Simple Way to Find Out Differences Between Sequences / File Contents using Python by Sunny Solanki
August 27, 2022 - As a part of our tenth example, we'll explain the usage of function ndiff() of module difflib which gives the same functionality that is available through Differ instance.
🌐
Python Module of the Week
pymotw.com › 2 › difflib
difflib – Compare sequences - Python Module of the Week
import difflib from difflib_data import * diff = difflib.ndiff(text1_lines, text2_lines) print '\n'.join(list(diff)) The processing is specifically tailored for working with text data and eliminating “noise” in the input. $ python difflib_ndiff.py Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Top answer
1 of 3
6

I'm also still trying to figure out why many difflib functions return a generator instead of a list, what's the advantage there?

Well, think about it for a second - if you compare files, those files can in theory (and will be in practice) be quite large - returning the delta as a list, for exampe, means reading the complete data into memory, which is not a smart thing to do.

As for only returning the difference, well, there is another advantage in using a generator - just iterate over the delta and keep whatever lines you are interested in.

If you read the difflib documentation for Differ - style deltas, you will see a paragraph that reads:

Each line of a Differ delta begins with a two-letter code:
Code    Meaning
'- '    line unique to sequence 1
'+ '    line unique to sequence 2
'  '    line common to both sequences
'? '    line not present in either input sequence

So, if you only want differences, you can easily filter those out by using str.startswith

You can also use difflib.context_diff to obtain a compact delta which shows only the changes.

2 of 3
4

Diffs must contain enough information to make it possible to patch a version into another, so yes, for your experiment of a single-line change to a very small document, storing the whole documents could be cheaper.

Library functions return iterators to make it easier on clients that are tight on memory or only need to look at part of the resulting sequence. It's ok in Python because every iterator can be converted to a list with a very short list(an_iterator) expression.

Most differencing is done on lines of text, but it is possible to go down to the char-by-char, and difflib does it. Take a look at the Differ class of object in difflib.

The examples all over the place use human-friendly output, but the diffs are managed internally in a much more compact, computer-friendly way. Also, diffs usually contain redundant information (like the text of a line to delete) to make patching and merging changes safe. The redundancy can be removed by your own code, if you feel comfortable with that.

I just read that difflib opts for least-surprise in favor of optimality, which is something I won't argue against. There are well known algorithms that are fast at producing a minimum set of changes.

I once coded a generic diffing engine along with one of the optimum algorithms in about 1250 lines of Java (JRCS). It works for any sequence of elements that can be compared for equality. If you want to build your own solution, I think that a translation/reimplementation of JRCS should take no more than 300 lines of Python.

Processing the output produced by difflib to make it more compact is also an option. This is an example from a small files with three changes (an addition, a change, and a deletion):

---  
+++  
@@ -7,0 +7,1 @@
+aaaaa
@@ -9,1 +10,1 @@
-c= 0
+c= 1
@@ -15,1 +16,0 @@
-    m = re.match(code_re, text)

What the patch says can be easily condensed to:

+7,1 
aaaaa
-9,1 
+10,1
c= 1
-15,1

For your own example the condensed output would be:

-8,1
+9,1
print "The end"

For safety, leaving in a leading marker ('>') for lines that must be inserted might be a good idea.

-8,1
+9,1
>print "The end"

Is that closer to what you need?

This is a simple function to do the compacting. You'll have to write your own code to apply the patch in that format, but it should be straightforward.

def compact_a_unidiff(s):
    s = [l for l in s if l[0] in ('+','@')]
    result = []
    for l in s:
        if l.startswith('++'):
            continue
        elif l.startswith('+'):
            result.append('>'+ l[1:])
        else:
            del_cmd, add_cmd = l[3:-3].split()
            del_pair, add_pair = (c.split(',') for c in (del_cmd,add_cmd))
            if del_pair[1]  != '0':
                result.append(del_cmd)
            if add_pair[1] != '0':
                result.append(add_cmd)
    return result
🌐
W3Schools
w3schools.com › python › ref_module_difflib.asp
Python difflib Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... import difflib words = ["ape", "apple", "peach", "puppy"] print(difflib.get_close_matches("appel", words, n=1)) Try it Yourself »
🌐
Real Python
realpython.com › ref › stdlib › difflib
difflib | Python Standard Library – Real Python
>>> import difflib >>> difflib.get_close_matches("pythn", ["python", "perl", "ruby"]) ['python'] Computes similarity ratios between any two sequences with SequenceMatcher · Generates unified diff output suitable for patch files with unified_diff() Produces human-readable line-by-line deltas with Differ and ndiff() Creates HTML tables for side-by-side comparison with HtmlDiff ·
🌐
Parseltongue
parseltongue.co.in › exploring-the-difflib-module-in-python
ParselTongue - Exploring the difflib Module in Python
July 26, 2024 - import difflib word = "ape" words_list = ["apple", "grapes", "ape", "cat", "app"] matches = difflib.get_close_matches(word, words_list) print(matches) ... The ndiff function compares sequences of lines of text and produces a human-readable delta.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › compare-sequences-in-python-using-dfflib-module
Compare sequences in Python using dfflib module - GeeksforGeeks
February 24, 2021 - # import required module import difflib # assign parameters par1 = 'Geeks' par2 = 'geeks!' # compare parameters for ele in difflib.ndiff(par1, par2): print(ele)
🌐
CodeRivers
coderivers.org › blog › difflib-python
Mastering `difflib` in Python: A Comprehensive Guide - CodeRivers
February 22, 2026 - In the above code: 1. We import the difflib library. 2. Define two sample strings text1 and text2. 3. Use difflib.ndiff to compare the two strings after splitting them into words. 4. Iterate over the differences and print each line.
🌐
Python Pool
pythonpool.com › home › blog › learn python difflib library effectively
Learn Python Difflib Library Effectively - Python Pool
March 23, 2022 - Learn about python's difflib library. Understand the working of its classes and functions. Learn about classes like differ & sequencematcher
🌐
Linux Hint
linuxhint.com › difflib-module-python
Linux Hint – Linux Hint
August 11, 2021 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Medium
medium.com › @zhangkd5 › a-tutorial-for-difflib-a-powerful-python-standard-library-to-compare-textual-sequences-096d52b4c843
A Tutorial of Difflib — A Powerful Python Standard Library to Compare Textual Sequences | by Kaidong Zhang | Medium
January 27, 2024 - To make the content more in-depth, I have prepared a simple exercise for you. In this section, you will try to use various different functions in difflib to experience its power. Open your Python environment and import difflib.
🌐
Kite
kite.com › python › docs › difflib.ndiff
Kite is saying farewell - Code Faster with Kite
November 20, 2022 - P.S. Most of our code has been open sourced on Github here. It includes our data-driven Python type inference engine, Python public-package analyzer, desktop software, editor integrations, Github crawler and analyzer, and much more.
🌐
ProgramCreek
programcreek.com › python › example › 1084 › difflib.Differ
Python Examples of difflib.Differ
The following are 30 code examples of difflib.Differ(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ...
🌐
Python
docs.python.org › 3.8 › library › difflib.html
difflib — Helpers for computing deltas — Python 3.8.20 documentation
Given a sequence produced by Differ.compare() or ndiff(), extract lines originating from file 1 or 2 (parameter which), stripping off line prefixes.
🌐
Java Guides
javaguides.net › 2024 › 12 › python-difflib-module.html
Python difflib Module - A Complete Guide
December 10, 2024 - ndiff · restore · IS_CHARACTER_JUNK ... · References · The difflib module provides a variety of classes and functions to compare sequences, find differences, and produce human-readable diff outputs....
🌐
Beautiful Soup
tedboy.github.io › python_stdlib › generated › difflib.html
difflib — Python Standard Library
Module difflib – helpers for computing deltas between objects. Function get_close_matches(word, possibilities, n=3, cutoff=0.6): Use SequenceMatcher to return list of the best “good enough” matches. ... For two lists of strings, return a delta in context diff format. ... Return a delta: the difference between a and b (lists of strings). ... Return one of the two sequences that generated an ndiff delta.