How can I find same values in a list and group together a new list?

Use itertools.groupby:

from itertools import groupby

N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]

print([list(j) for i, j in groupby(N)])

Output:

[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

Side note: Prevent from using global variable when you don’t need to.

Leave a Comment