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,910 points
6,229 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,300 points

Related Questions In Python

+1 vote
8 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
35,871 views
+1 vote
4 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, 2020 in Python by sahil
• 580 points
280,260 views
0 votes
3 answers

How can I sort a dictionary by key in python?

Another way could be: color_dict = {'red':'#FF0000',           'green':'#008000',           'black':'#000000',           'white':'#FFFFFF'} for ...READ MORE

answered Dec 28, 2020 in Python by Thomas Walenta
1,064 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
35,301 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,363 views
0 votes
1 answer
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, 2020 in Python by sahil
• 580 points
1,731 views
0 votes
1 answer

How to Reverse a list in Python

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

answered Sep 29, 2018 in Python by SDeb
• 13,300 points
794 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP