How to Group Consecutive Equal Elements in Python
Group consecutive equal elements in a list into sublists using itertools.groupby.
Python code
11 linesfrom itertools import groupby
def group_consecutive(lst):
"""Group consecutive equal elements into sublists."""
return [list(group) for _, group in groupby(lst)]
if __name__ == "__main__":
input_list = [1, 1, 2, 2, 2, 3, 1, 1, 4, 4, 4, 4]
result = group_consecutive(input_list)
print("Input:", input_list)
print("Output:", result)
Output
Input: [1, 1, 2, 2, 2, 3, 1, 1, 4, 4, 4, 4]
Output: [[1, 1], [2, 2, 2], [3], [1, 1], [4, 4, 4, 4]]
How it works
The groupby function from the itertools module groups consecutive identical elements without needing a loop. It returns pairs of (key, iterator), so we discard the key with _ and convert each iterator to a list. This approach efficiently processes the list in a single pass, grouping only adjacent duplicates, not all equal elements. The result is a list of sublists preserving the original order of groups.
Common mistakes
- Using `set()` or sorting which groups all equal elements, not just consecutive ones.
- Forgetting that `groupby` requires the list to be sorted or pre-grouped; it only groups adjacent equal values.
- Mutating the list while iterating over it with groupby, which causes unexpected behavior.
- Omitting `list()` around each group and getting iterator objects instead of lists.
Variations
- Use a manual loop with while to group without importing itertools.
- Apply groupby with a custom key function to group by a transformation of each element.
Real-world use cases
- Compressing run-length encoding (RLE) for image or binary data storage.
- Grouping consecutive identical sensor readings to detect stable states in IoT data.
- Aggregating consecutive same-day transactions into batches for financial reporting.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.