Although the other answers are correct, here's another approach without using any outside package in a simple understandable manner -
lst= ['Red','Green','Yellow','Blue','Blue','Green','Red','Yellow','Purple']
dictionary = {}
# Store the frequency of each element that occurs in list
for i in lst :
if(dictionary.get(i)==None):
dictionary[i]=1
else :
dictionary[i]+=1
ans=[]
# Generate the final answer by making list with each element occurring according to their frequency
for k in dictionary.keys():
tmp = [k]*dictionary[k]
ans.append(tmp)
print(ans)
Output :
[['Red', 'Red'], ['Green', 'Green'], ['Yellow', 'Yellow'], ['Blue', 'Blue'], ['Purple']]
Or, if you don't want to generate 2-d list, you can directly print the list of each element where they occur their frequency number of times respectively as -
lst= ['Red','Green','Yellow','Blue','Blue','Green','Red','Yellow','Purple']
dictionary = {}
# Same as in last example... just a more pythonic way of doing it
for i in lst :
dictionary[i]=dictionary.get(i,0)+1
for k in dictionary.keys():
elements = [k]*dictionary[k]
print(elements)
Output :
['Red', 'Red']
['Green', 'Green']
['Yellow', 'Yellow']
['Blue', 'Blue']
['Purple']
You will get the exact output as you had asked in the question. This would be the best way if you are willing to accomplish the task without any external packages.