- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to pack same consecutive elements into sublist in Python

Suppose we have a list of numbers nums, we will pack consecutive elements of the same value into sublists. We have to keep in mind that there is only one occurrence in the list it should still be in its own sublist.

So, if the input is like nums = [5, 5, 2, 7, 7, 7, 2, 2, 2, 2], then the output will be [[5, 5], [2], [7, 7, 7], [2, 2, 2, 2]]

To solve this, we will follow these steps −

- if nums is empty, then
- return a new list

- result := a list with another list that contains nums[0]
- j := 0
- for i in range 1 to size of nums, do
- if nums[i] is not same as nums[i - 1], then
- insert a new list at the end of result
- j := j + 1

- insert nums[i] at the end of result[j]

- if nums[i] is not same as nums[i - 1], then
- return result

Let us see the following implementation to get better understanding −

## Example

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 ob = Solution() nums = [5, 5, 2, 7, 7, 7, 2, 2, 2, 2] print(ob.solve(nums))

## Input

[5, 5, 2, 7, 7, 7, 2, 2, 2, 2]

## Output

[[5, 5], [2], [7, 7, 7], [2, 2, 2, 2]]

- Related Articles
- Program to find length of longest consecutive sublist with unique elements in Python
- Program to find numbers with same consecutive differences in Python
- Python program to count pairs for consecutive elements
- Program to remove sublist to get same number of elements below and above k in C++
- Program to find length of longest alternating inequality elements sublist in Python
- Program to find a sublist where first and last values are same in Python
- Program to find length of longest contiguous sublist with same first letter words in Python
- Program to find length of shortest sublist with maximum frequent element with same frequency in Python
- Swap Consecutive Even Elements in Python
- Python – Filter consecutive elements Tuples
- Python – Reorder for consecutive elements
- Python – Consecutive identical elements count
- Consecutive elements pairing in list in Python
- Python Program to Sort Matrix Rows by summation of consecutive difference of elements
- Program to check whether we can split a string into descending consecutive values in Python

Advertisements