The get_opcodes() method of SequenceMatcher class

The get_opcodes() method of the SequenceMatcher class provides a list of opcodes - replace, delete, insert, equal - which are required for making a sequence1 into sequence2.

Sequencematcher Updated 24 Feb 2026 1 min read

Overview

  • Using the operations replace, delete, insert and equal a sequence s1 can be transformed into another sequence s2.

  • The get_opcodes() returns the required number of operations to transform one sequence into another as a list of tuples. Each tuple contains one opcode.

  1. Each tuple consists of the following information:
    An opcode describing the operation to be performed on the substring of sequence – s1. An opcode assumes one of the following values ‘replace’, ‘delete’, ‘insert’ and ‘equal’.
  2. The start index of the substring of sequence s1
  3. The end index of the substring of sequence s1
  4. The start index of the substring of sequence s2
  5. The end index of the substring of sequence s2

In Python, a substring of s is denoted as string[start:end] where start index is included in the substring and the end index is not included in the substring.

Example

python
# Example Python program that gets the opcodes

            # to make sequence1 into sequence2 using the

            # get_opcodes() method of the SequenceMatcher object

            import difflib

# The sequences

            string1 = "Humpty Dumpty sat on a wall"

            string2 = "Humpty Dumpty had a great fall"

# Create a SequenceMatcher object

            seqMatcher = difflib.SequenceMatcher()

# Set the sequences to the SequenceMatcher

            seqMatcher.set_seq1(string1)

            seqMatcher.set_seq2(string2)

# Get the opcodes

            opCodes = seqMatcher.get_opcodes()

print("The opcodes to turn string1 into string2:")

            print(opCodes)

Output

Output
The opcodes to turn string1 into string2:

            [('equal', 0, 14, 0, 14), ('replace', 14, 15, 14, 23), ('equal', 15, 18, 23, 26), ('replace', 18, 24, 26, 27), ('equal', 24, 27, 27, 30)]