Levenshtein Distance Implementation in Python
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 in Python: what you actually reach for
Python implementation
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 FreeThe Python-specific trap
Performance in Python, beyond the O(n*m)
Real-World Applications
Interview Tips & Practice
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).
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 trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.