Python Practice › List Programs › Program 55

Pack consecutive duplicates

EasyList Programs · 55 of 100

Write a Python program to pack consecutive duplicates into sublists.

Advertisement
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

  1. itertools.groupby groups consecutive equal items.

Solution

Python
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]]
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs