Python – Reorder for consecutive elements


When it is required to reorder consecutive elements, the ‘Counter’ method, an empty list and a simple iteration are used.

Example

Below is a demonstration of the same

from collections import Counter

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

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

my_frequencys = Counter(my_list)
my_result = []

for value, count in my_frequencys.items():
   my_result.extend([value]*count)

print("The resultant list is :")
print(my_result)

Output

The list is :
[21, 83, 44, 52, 61, 72, 81, 96, 18, 44]
The resultant list is :
[21, 83, 44, 44, 52, 61, 72, 81, 96, 18]

Explanation

  • The required packages are imported into the environment.

  • A list is defined and is displayed on the console.

  • A ‘Counter’ of the list is defined and assigned to a variable.

  • An empty list is created.

  • The elements of the variable are accessed, and the product of the count of the element and the element are appended to the empty list.

  • This is the output that is displayed on the console.

Updated on: 14-Sep-2021

79 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements