
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reorder for Consecutive Elements in Python
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.
Advertisements