How to Group Consecutive Equal Elements in Python

Group consecutive equal elements in a list into sublists using itertools.groupby.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 16 views 0 copies

Python code

11 lines
Python 3.9+
from 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

stdout
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

  1. Use a manual loop with while to group without importing itertools.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.