Sort list by frequency in python

0 votes
How do I sort a list by its frequency in Python?

For example, I have the list:

[1,2,3,4,3,3,3,6,7,1,1,9,3,2]
 

The above list would be sorted in the order of the frequency of its values to create the following list, where the item with the greatest frequency is placed at the front:

[3,3,3,3,3,1,1,1,2,2,4,6,7,9]
May 13, 2019 in Python by ana1504.k
• 7,890 points
1,632 views

1 answer to this question.

0 votes
You can try the following for a collections.Counter:

counts = collections.Counter(lst)
new_list = sorted(lst, key=lambda x: -counts[x])
 

Alternatively, you could write the second line without a lambda:

counts = collections.Counter(lst)
new_list = sorted(lst, key=counts.get, reverse=True)
answered May 13, 2019 by SDeb
• 13,250 points

Related Questions In Python

+1 vote
7 answers

Count the frequency of an item in a python list

To count the number of appearances: from collections ...READ MORE

answered Oct 18, 2018 in Python by tinitales
8,389 views
0 votes
2 answers

How do I remove an element from a list by index in Python?

Delete the List and its element: We have ...READ MORE

answered Jun 7 in Python by sahil
• 540 points
22,843 views
+4 votes
7 answers

Splitting a List into chunks in Python

Here's a generator that yields the chunks ...READ MORE

answered Apr 13, 2018 in Python by Nietzsche's daemon
• 4,260 points
22,782 views
0 votes
1 answer

How can I convert a list of dictionaries from a CSV into a JSON object in Python?

You could try using the AST module. ...READ MORE

answered Apr 17, 2018 in Python by anonymous
1,799 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,196 views
0 votes
0 answers
0 votes
2 answers

In Python, how do I read a file line-by-line into a list?

readline function help to  read line in ...READ MORE

answered Jun 21 in Python by sahil
• 540 points
239 views
0 votes
1 answer

How to Reverse a list in Python

You can use the reversed function in ...READ MORE

answered Sep 28, 2018 in Python by SDeb
• 13,250 points
157 views