Problem No 19
Group equal consecutive values into sublists
Hard≈ 25 minute session
Lesson guide
What this Python exercise practices
Group equal consecutive values into sublists is a advanced practice lesson that focuses on loops, iteration, counters. It is designed to be solved in about 25 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Lists or strings
- Basic for loop syntax
Difficulty and time
- Level
- Advanced
- Estimated time
- 25 minutes
Practice path
Summary
Group runs of consecutive equal values in a list into sublists, preserving order and element types.
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]]
Explanation
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]]
Explanation
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 input 0
["a", "a", "b", "b", "a"]
Sample output 0
[['a', 'a'], ['b', 'b'], ['a']]
Explanation 0
The last 'a' is not consecutive with the first two, so it starts a new run.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.