Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Program to pack same consecutive elements into sublist in Python
Sometimes we need to group consecutive elements of the same value into sublists. This is useful for data analysis, compression, or pattern recognition tasks.
Given a list like [5, 5, 2, 7, 7, 7, 2, 2, 2, 2], we want to create sublists for each group of consecutive identical elements: [[5, 5], [2], [7, 7, 7], [2, 2, 2, 2]].
Algorithm Steps
The approach follows these steps ?
- If the input list is empty, return an empty list
- Initialize result with first element in its own sublist
- Iterate through remaining elements
- If current element differs from previous, start new sublist
- Otherwise, add to current sublist
Implementation Using Class Method
class Solution:
def solve(self, nums):
if not nums:
return []
result = [[nums[0]]]
j = 0
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
result.append([])
j += 1
result[j].append(nums[i])
return result
# Test the solution
ob = Solution()
nums = [5, 5, 2, 7, 7, 7, 2, 2, 2, 2]
print(ob.solve(nums))
[[5, 5], [2], [7, 7, 7], [2, 2, 2, 2]]
Using itertools.groupby()
Python's itertools.groupby() provides a more concise solution ?
from itertools import groupby
def pack_consecutive(nums):
return [list(group) for key, group in groupby(nums)]
# Test with same data
nums = [5, 5, 2, 7, 7, 7, 2, 2, 2, 2]
result = pack_consecutive(nums)
print(result)
[[5, 5], [2], [7, 7, 7], [2, 2, 2, 2]]
Simple Function Approach
A straightforward function without using classes ?
def pack_same_elements(nums):
if not nums:
return []
result = []
current_group = [nums[0]]
for i in range(1, len(nums)):
if nums[i] == nums[i-1]:
current_group.append(nums[i])
else:
result.append(current_group)
current_group = [nums[i]]
result.append(current_group)
return result
# Test with different examples
test_cases = [
[1, 1, 2, 3, 3, 3, 4],
[1],
[1, 2, 3, 4],
[]
]
for nums in test_cases:
print(f"Input: {nums}")
print(f"Output: {pack_same_elements(nums)}")
print()
Input: [1, 1, 2, 3, 3, 3, 4] Output: [[1, 1], [2], [3, 3, 3], [4]] Input: [1] Output: [[1]] Input: [1, 2, 3, 4] Output: [[1], [2], [3], [4]] Input: [] Output: []
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Manual Loop | Clear logic | O(n) | Learning/Understanding |
| itertools.groupby() | Very concise | O(n) | Production code |
| Simple Function | Most readable | O(n) | General use |
Conclusion
Use itertools.groupby() for the most Pythonic solution, or implement manually for better understanding. All approaches handle edge cases like empty lists and single elements correctly.
Advertisements
