Python Practice › List Programs › Program 55
Pack consecutive duplicates
Write a Python program to pack consecutive duplicates into sublists.
Input
[0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]
Output
[[0, 0], [1], [2], [3], [4, 4], [5], [6, 6], [7], [8, 8], [9]]
Approach
itertools.groupbygroups consecutive equal items.
Solution
from itertools import groupby data = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9]print([list(group) for _, group in groupby(data)])Output
[[0, 0], [1], [2], [3], [4, 4], [5], [6, 6], [7], [8, 8], [9]]
Learn the concept
New to this topic? Read the lesson, then come back.