Python | Identical Consecutive Grouping in list

Python | Identical Consecutive Grouping in list

Grouping identical consecutive elements in a list involves segregating sequences of repeated elements into separate lists. This tutorial will guide you on how to achieve this in Python.

Problem Statement:

Given a list:

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

You want to group identical consecutive elements:

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

Tutorial:

Method 1: Using itertools.groupby()

The groupby() function from the itertools module makes this task straightforward. It groups consecutive identical elements in a given iterable.

from itertools import groupby lst = [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 5, 1, 1] result = [list(group) for _, group in groupby(lst)] print(result) # Outputs: [[1, 1, 1], [2, 2], [3, 3, 3, 3], [4], [5, 5], [1, 1]] 

Method 2: Using a Loop

You can achieve this with a loop by iterating through the list and grouping consecutive identical elements.

lst = [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 5, 1, 1] result = [] current_group = [lst[0]] for i in range(1, len(lst)): if lst[i] == lst[i-1]: current_group.append(lst[i]) else: result.append(current_group) current_group = [lst[i]] result.append(current_group) print(result) # Outputs: [[1, 1, 1], [2, 2], [3, 3, 3, 3], [4], [5, 5], [1, 1]] 

Conclusion:

Grouping identical consecutive elements in a list in Python can be accomplished either by utilizing the groupby() function from the itertools module or with a simple loop. The choice of method often depends on one's familiarity with the available tools and the specific requirements of the task.


More Tags

location-provider integration-testing avfoundation controller jquery-ui-datepicker radio-button items child-process criteria-api sigpipe

More Programming Guides

Other Guides

More Programming Examples