Python Practice › List Programs › Program 98
Decode a run-length encoded list
Write a Python program to decode a run-length encoded list, where [n, x] means x repeated n times.
Input
[[2, 1], 2, 3, [2, 4], 5, 1]
Output
[1, 1, 2, 3, 4, 4, 5, 1]
Approach
- Expand [n, x] pairs; copy plain items.
Solution
encoded = [[2, 1], 2, 3, [2, 4], 5, 1]decoded = []for item in encoded: if isinstance(item, list): count, value = item decoded.extend([value] * count) else: decoded.append(item)print(decoded)Output
[1, 1, 2, 3, 4, 4, 5, 1]
Line by line
Lines 5-6
[value] * count repeats the value.
Learn the concept
New to this topic? Read the lesson, then come back.