Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Levenshtein Distance Implementation in Python

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Levenshtein Distance runs in O(n*m) time and O(n*m) space, in Python as in every other language.
  • ✓CPython ships no Levenshtein. difflib.SequenceMatcher and difflib.get_close_matches implement Ratcliff/Obershelp gestalt matching, which is a similarity ratio, not an edit distance, and its ratio() is not 1 - dist/len.
  • ✓Reviewers reject the full matrix in Python and ask for two rows swapped by tuple assignment, because the object overhead per cell hurts long before the big-O does.
  • ✓The Python trap: dp = [[0] * (m + 1)] * (n + 1) builds one row and n+1 references to that same list, so dp[i][j] = v writes every row at once.
  • ✓Pure Python costs roughly two orders of magnitude over a C loop: every cell is a bytecode dispatch plus a comparison on boxed objects.

What Levenshtein Distance actually is

Levenshtein distance is the minimum number of single-character insertions, deletions and substitutions that turn one string into another: kitten to sitting is 3. The standard solution fills an (n+1)x(m+1) table where every cell is the cheapest of its three neighbours, giving O(n*m) time and O(n*m) space that reduces to two rows when you only need the number. Engineers reach for it in fuzzy search and spell correction, in deduplicating near-identical customer records, and in matching noisy identifiers where an exact string compare is too brittle and a hash is useless.

Levenshtein Distance in Python: what you actually reach for

CPython ships no Levenshtein. difflib.SequenceMatcher and difflib.get_close_matches implement Ratcliff/Obershelp gestalt matching, which is a similarity ratio, not an edit distance, and its ratio() is not 1 - dist/len. For the real metric the ecosystem standard is rapidfuzz: from rapidfuzz.distance import Levenshtein, then Levenshtein.distance(a, b). It is a C++ extension under MIT and it absorbed the old GPL python-Levenshtein, which is why it won. It takes a score_cutoff to bail out early. Hand-rolled tables use plain lists, array.array('i'), or functools.lru_cache over a recursive form.

Python implementation

Reviewers reject the full matrix in Python and ask for two rows swapped by tuple assignment, because the object overhead per cell hurts long before the big-O does. They want min() over three terms rather than nested ifs, the bare (a != b) as the substitution cost (bool is an int subclass, so no int() cast is needed), and enumerate(seq, start=1) instead of range(len(...)) indexing. Type the parameters generically, T = TypeVar('T') with def levenshtein(a: Sequence[T], b: Sequence[T]) -> int, so the same function diffs token lists and not just str; the algorithm calls __eq__ only and never __hash__, so Sequence[Hashable] would demand a capability it does not use.
python
from typing import Sequence, TypeVar

T = TypeVar("T")


def levenshtein(a: Sequence[T], b: Sequence[T]) -> int:
    if len(a) < len(b):
        a, b = b, a
    if not b:
        return len(a)
    prev = list(range(len(b) + 1))
    cur = [0] * (len(b) + 1)
    for i, ca in enumerate(a, start=1):
        cur[0] = i
        for j, cb in enumerate(b, start=1):
            # bool is an int in Python: (ca != cb) is the substitution cost
            cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb))
        prev, cur = cur, prev
    return prev[len(b)]


if __name__ == "__main__":
    from unicodedata import normalize
    print(levenshtein("kitten", "sitting"))                      # 3
    nfd, nfc = "cafe\u0301", "caf\u00e9"      # these two render identically
    print(levenshtein(nfd, nfc))                                      # 2: substitute, then insert
    print(levenshtein(normalize("NFC", nfd), normalize("NFC", nfc)))  # 0

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Python-specific trap

dp = [[0] * (m + 1)] * (n + 1) builds one row and n+1 references to that same list, so dp[i][j] = v writes every row at once. The distance comes out wrong and nothing raises. The comprehension form [[0] * (m + 1) for _ in range(n + 1)] is the fix. The second silent bug is that str iterates by code point, so 'cafe' with a combining acute is 5 items and the precomposed spelling is 4, so two strings that render identically come back at distance 2, one substitution plus one insertion, rather than 0. Run unicodedata.normalize('NFC', s) on both sides first. Neither bug shows up in an ASCII unit test.

Performance in Python, beyond the O(n*m)

Pure Python costs roughly two orders of magnitude over a C loop: every cell is a bytecode dispatch plus a comparison on boxed objects. CPython interns small ints in -5..256, so cells stay cheap, but the min() call and the index loads dominate. Two flat lists beat a nested list (one fewer indirection per read); array.array('i') halves memory but not time, because each read boxes a fresh int. Past a few thousand pairs, switch to rapidfuzz, whose bit-parallel Myers kernel does O(n*m/64) word operations. The asymptotic cost is the same in every language, O(n*m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Levenshtein Distance between languages.

Real-World Applications

Levenshtein Distance applies wherever its problem shape appears in your own code. In Python, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Levenshtein Distance helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Levenshtein Distance appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Levenshtein Distance over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Levenshtein Distance to build pattern recognition. In Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

Frequently Asked Questions

Which Python type or library should I use for Levenshtein Distance?

CPython ships no Levenshtein. difflib.SequenceMatcher and difflib.get_close_matches implement Ratcliff/Obershelp gestalt matching, which is a similarity ratio, not an edit distance, and its ratio() is not 1 - dist/len. For the real metric the ecosystem standard is rapidfuzz: from rapidfuzz.distance import Levenshtein, then Levenshtein.distance(a, b). It is a C++ extension under MIT and it absorbed the old GPL python-Levenshtein, which is why it won. It takes a score_cutoff to bail out early. Hand-rolled tables use plain lists, array.array('i'), or functools.lru_cache over a recursive form.

What is the most common Python mistake when implementing Levenshtein Distance?

dp = [[0] * (m + 1)] * (n + 1) builds one row and n+1 references to that same list, so dp[i][j] = v writes every row at once. The distance comes out wrong and nothing raises. The comprehension form [[0] * (m + 1) for _ in range(n + 1)] is the fix. The second silent bug is that str iterates by code point, so 'cafe' with a combining acute is 5 items and the precomposed spelling is 4, so two strings that render identically come back at distance 2, one substitution plus one insertion, rather than 0. Run unicodedata.normalize('NFC', s) on both sides first. Neither bug shows up in an ASCII unit test.

How does Levenshtein Distance actually perform in Python?

Pure Python costs roughly two orders of magnitude over a C loop: every cell is a bytecode dispatch plus a comparison on boxed objects. CPython interns small ints in -5..256, so cells stay cheap, but the min() call and the index loads dominate. Two flat lists beat a nested list (one fewer indirection per read); array.array('i') halves memory but not time, because each read boxes a fresh int. Past a few thousand pairs, switch to rapidfuzz, whose bit-parallel Myers kernel does O(n*m/64) word operations. Time complexity is O(n*m) and space is O(n*m).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying for GitHub Copilot, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.