Run-Length Encoding 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
- ✓Run-Length Encoding runs in O(n) time and O(n) space, in Python as in every other language.
- ✓itertools.groupby (from itertools import groupby) is the RLE primitive: called with no key it yields (value, group_iterator) for every maximal run of adjacent equal items, which is precisely a run.
- ✓Reviewers want groupby rather than a hand-rolled index loop, and ''.join(parts) rather than out += part.
- ✓The Python trap: groupby's group iterator is a view over the SAME underlying iterator, not a copy. The instant you advance to the next (key, group) pair, the previous group is silently exhausted.
- ✓CPython's groupby is C code, so it beats an equivalent Python-level loop by a large constant even though both are O(n).
What Run-Length Encoding actually is
Run-Length Encoding in Python: what you actually reach for
Python implementation
from itertools import groupby
def encode(s: str) -> str:
parts = []
for ch, grp in groupby(s):
n = sum(1 for _ in grp) # consume grp NOW, not later
parts.append(ch if n == 1 else f"{ch}{n}")
return "".join(parts)
DIGITS = "0123456789" # str.isdigit() also accepts '²' and '٣'
def decode(s: str) -> str:
parts, i, end = [], 0, len(s)
while i < end:
ch = s[i]
i += 1
j = i
while j < end and s[j] in DIGITS:
j += 1
parts.append(ch * (int(s[i:j]) if j > i else 1))
i = j
return "".join(parts)
assert encode("aaabbc") == "a3b2c"
assert decode(encode("aaabbc")) == "aaabbc"
assert [k for k, _ in groupby("aab")] == ["a", "b"]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)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Run-Length Encoding?
itertools.groupby (from itertools import groupby) is the RLE primitive: called with no key it yields (value, group_iterator) for every maximal run of adjacent equal items, which is precisely a run. Accumulate into a list and finish with str.join. For binary payloads groupby still works because bytes iterates as int, and memoryview avoids the slice copies. The regex route is re.finditer(r'(.)\1*', s, re.S): each match is one whole run, and re.DOTALL is mandatory or a run of newlines is skipped entirely.
What is the most common Python mistake when implementing Run-Length Encoding?
groupby's group iterator is a view over the SAME underlying iterator, not a copy. The instant you advance to the next (key, group) pair, the previous group is silently exhausted. So list(groupby(s)) hands you keys attached to empty groups, and [(k, len(list(g))) for k, g in groupby(s)] only works because the comprehension consumes g before stepping. Reorder it, stash the groups in a dict, or sort by count first, and every count becomes 0. No exception, no warning: you get a0b0c0 and a green test on the empty-string case.
How does Run-Length Encoding actually perform in Python?
CPython's groupby is C code, so it beats an equivalent Python-level loop by a large constant even though both are O(n). ''.join(parts) sums the lengths and allocates once. out += ch looks fine because CPython special-cases an in-place resize when the string's refcount is 1, but that is a CPython implementation detail: it vanishes under PyPy, and the moment anything else holds a reference you are back to quadratic copying. Memory: an all-ASCII str is stored at one byte per character, and a single astral character promotes the whole object to four. Time complexity is O(n) and space is O(n).
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 trialIf you are a student, see what Devin offers students for free 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.