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
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:
-
Counter(my_list)creates a dictionary with element frequencies - We iterate through each unique value and its count
-
extend([value] * count)adds the element repeated by its frequency count - 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.
