# Python Program for sorting elements of an Array by Frequency

## Sorting elements of an Array by Frequency in Python

Here, in this article we will discuss the program for sorting elements of an array by frequency in python programming language. We will discuss various algorithms for sorting.

Here, we will discuss the following methods in this page.

• Method 1 : Using Collections.counter()
• Method 2 : Using Iterables.
• Method 3 : Using sorted() inbuilt function.

Let’s discuss above three methods one by one,

## Method 1 :

In this method we will use Collections.counter() to count the occurrence of element present in the list.

### Method 1 : Code in Python

Run
```from collections import Counter
ini_list = [10, 20, 30, 40, 40, 50, 50, 50]

# sorting on bais of frequency of elements
result = [item for items, c in Counter(ini_list).most_common() for item in [items] * c]

# printing final result
print(str(result))```

### Output

`[50, 50, 50, 40, 40, 10, 20, 30]`

## Method 2 :

In this method we will use iterables for sorting on the basis of frequency of elements.

### Method 2 : Code in Python

Run
```from collections import Counter
from itertools import repeat, chain
ini_list = [10, 20, 30, 40, 40, 50, 50, 50]

# sorting on bais of frequency of elements
result = list(chain.from_iterable(repeat(i, c) for i, c in Counter(ini_list).most_common()))

# printing final result
print(str(result))
```

### Output

`[50, 50, 50, 40, 40, 10, 20, 30]`

## Method 3 :

In this method we will use sorted() inbuilt function.

### Method 3 : Code in Python

Run
```from collections import Counter
from itertools import repeat, chain
ini_list = [10, 20, 30, 40, 40, 50, 50, 50]

# sorting on bais of frequency of elements
result = sorted(ini_list, key = ini_list.count, reverse = True)

# printing final result
print(str(result))```

### Output

`[50, 50, 50, 40, 40, 10, 20, 30]`

### One comment on “Python Program for sorting elements of an Array by Frequency”

• SUMAN

def frequency(arr,n):
visited = [False for i in range(n)];
for i in range(n):
if (visited[i] == True) :
continue

count = 1;
for j in range(i+1,n,1):
if (arr[i] == arr[j]) :
visited[j] = True
count += 1;
print(arr[i],count);
print(sorted(arr,reverse = True));
a1 = list(map(int,input().split(“,”)))
l = len(a1);
frequency(a1,l)