Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Group equal consecutive values into sublists

Group runs of consecutive equal values in a list into sublists, preserving order and element types.

Python practice25 minLists & TuplesAdvancedLast updated March 17, 2026

Problem statement

Write a function group_consecutive(lst) that takes a list lst and returns a new list of lists. Each sublist should contain consecutive elements from lst that are equal to each other. The order of runs should match their order in the original list. If lst is empty, return an empty list. Elements can be of any type and equality should use Python's standard == operator.

Task

Given a list, return a list of sublists where each sublist contains a maximal consecutive run of equal values from the original list.

Examples

Basic numeric runs

Input

[1, 1, 2, 2, 2, 3]

Output

[[1, 1], [2, 2, 2], [3]]

Two 1s form the first run, three 2s the second, and a single 3 the last.

Different types and booleans

Input

[True, True, False, False, False]

Output

[[True, True], [False, False, False]]

Runs are formed using == equality; booleans group separately from other values.

Input format

A single argument: a list (possibly empty) of values.

Output format

Return a list of lists, where each inner list is a consecutive run of equal values.

Constraints

Do not use external libraries. Preserve the original element values and relative order. Time complexity should be O(n).

Samples

Sample 1

Input

["a", "a", "b", "b", "a"]

Output

[['a', 'a'], ['b', 'b'], ['a']]

The last 'a' is not consecutive with the first two, so it starts a new run.