Python – Reorder for consecutive elements

When working with lists in Python, you may need to reorder consecutive elements by grouping identical values together. This can be achieved using the Counter class from the collections module along with list iteration.

What is Reordering for Consecutive Elements?

Reordering for consecutive elements means rearranging a list so that all identical values appear together consecutively, while maintaining their original frequency count.

Using Counter for Reordering

The Counter class counts the frequency of each element, then we can reconstruct the list with grouped elements ?

from collections import Counter

my_list = [21, 83, 44, 52, 61, 72, 81, 96, 18, 44]

print("The original list is:")
print(my_list)

# Count frequency of each element
my_frequency = Counter(my_list)
my_result = []

# Group consecutive elements together
for value, count in my_frequency.items():
    my_result.extend([value] * count)

print("The reordered list is:")
print(my_result)
The original list is:
[21, 83, 44, 52, 61, 72, 81, 96, 18, 44]
The reordered list is:
[21, 83, 44, 44, 52, 61, 72, 81, 96, 18]

How It Works

The process involves these steps:

  1. Counter(my_list) creates a dictionary with element frequencies
  2. We iterate through each unique value and its count
  3. extend([value] * count) adds the element repeated by its frequency count
  4. All identical elements now appear consecutively in the result

Alternative Approach Using Sorting

You can also reorder consecutive elements by simply sorting the list ?

my_list = [21, 83, 44, 52, 61, 72, 81, 96, 18, 44]

print("Original list:")
print(my_list)

# Sort to group identical elements
sorted_list = sorted(my_list)

print("Sorted consecutive elements:")
print(sorted_list)
Original list:
[21, 83, 44, 52, 61, 72, 81, 96, 18, 44]
Sorted consecutive elements:
[18, 21, 44, 44, 52, 61, 72, 81, 83, 96]

Comparison

Method Order Preserved Best For
Counter First occurrence order Maintaining original sequence
sorted() Numerical/alphabetical Complete ordering

Conclusion

Use Counter to reorder consecutive elements while preserving the order of first occurrences. For complete sorting, use the sorted() function instead.

Updated on: 2026-03-26T01:49:52+05:30

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements