Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Step Frequency of elements in List
Next article icon

Sort List Elements by Frequency – Python

Last Updated : 12 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = [“Aryan”, “Harsh”, “Aryan”, “Kunal”, “Harsh”, “Aryan”] then the output should be: [‘Aryan’, ‘Aryan’, ‘Aryan’, ‘Harsh’, ‘Harsh’, ‘Kunal’] because “Aryan” occurs three times, “Harsh” occurs twice, and “Kunal” occurs once.

Using sorted() with collections.Counter 

We use collections.Counter to count the frequency of each element and then sort the list a based on the negative frequency (to get descending order) using sorted().

Python
from collections import Counter  a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"]  # Count frequency of each element in a freq = Counter(a)  # Sort list a based on frequency (highest frequency first) res = sorted(a, key=lambda x: -freq[x]) print(res) 

Output
['Aryan', 'Aryan', 'Aryan', 'Harsh', 'Harsh', 'Kunal'] 

Explanation: Counter object computes the frequency of each element in a and sorted() function sorts a using a lambda that returns the negative frequency of each element ensuring elements with higher counts come first.

Using Counter.most_common() with List Comprehension 

In this method we use Counter.most_common() to retrieve elements sorted by frequency and then rebuild the list by repeating each element according to its count.

Python
from collections import Counter  a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"]  freq = Counter(a) res = [] for item, count in freq.most_common():     res.extend([item] * count) print(res) 

Output
['Aryan', 'Aryan', 'Aryan', 'Harsh', 'Harsh', 'Kunal'] 

Explanation:

  • freq.most_common() returns a list of tuples, each containing an element and its count sorted from the highest to the lowest frequency.
  • The loop iterates over these tuples and for each, [item] * count creates a list with the element repeated as many times as it appears.
  • extend() method adds these repeated elements to the result list in order.

Using Naive Approach

We manually count the frequency of each element using a dictionary, sort the dictionary keys by their frequency in descending order and then reconstruct the sorted list.

Python
a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"]  # Manually count frequency of each element freq = {} for x in a:     freq[x] = freq.get(x, 0) + 1  # Sort the keys based on their frequency in descending order sorted_keys = sorted(freq.keys(), key=lambda x: freq[x], reverse=True)  # Rebuild the list by extending each key repeated by its frequency res = [] for key in sorted_keys:     res.extend([key] * freq[key])      print(res) 

Output
['Aryan', 'Aryan', 'Aryan', 'Harsh', 'Harsh', 'Kunal'] 

Explanation:

  • dictionary freq is built by iterating over a and counting each element.
  • The keys of freq are sorted in descending order based on their frequency using sorted() with the reverse=True flag.
  • Result list is then built by repeating each key (element) according to its frequency and extending the list in that order.


Next Article
Python - Step Frequency of elements in List
author
garg_ak0109
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python-sort
Practice Tags :
  • python

Similar Reads

  • Python - List Frequency of Elements
    We are given a list we need to count frequencies of all elements in given list. For example, n = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] we need to count frequencies so that output should be {4: 4, 3: 3, 2: 2, 1: 1}. Using collections.Countercollections.Counter class provides a dictionary-like structure that
    2 min read
  • Python - Restrict Elements Frequency in List
    Given a List, and elements frequency list, restrict frequency of elements in list from frequency list. Input : test_list = [1, 4, 5, 4, 1, 4, 4, 5, 5, 6], restrct_dict = {4 : 3, 1 : 1, 6 : 1, 5 : 1} Output : [1, 4, 5, 4, 4, 6] Explanation : Limit of 1 is 1, any occurrence more than that is removed.
    5 min read
  • Python - Step Frequency of elements in List
    Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let's discuss certain ways in which thi
    4 min read
  • Python - Elements frequency in Tuple
    Given a Tuple, find the frequency of each element. Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on.. Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on.. Method #1 Using def
    7 min read
  • Python - Sort by Frequency of second element in Tuple List
    Given list of tuples, sort by frequency of second element of tuple. Input : test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Output : [(1, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)] Explanation : 7 occurs 3 times as 2nd element, hence all tuples with 7, are aligned first. Input : test_l
    6 min read
  • Python | Group list elements based on frequency
    Given a list of elements, write a Python program to group list elements and their respective frequency within a tuple. Examples: Input : [1, 3, 4, 4, 1, 5, 3, 1] Output : [(1, 3), (3, 2), (4, 2), (5, 1)] Input : ['x', 'a', 'x', 'y', 'a', 'x'] Output : [('x', 3), ('a', 2), ('y', 1)] Method #1: List c
    5 min read
  • Python - Elements frequency in Tuple Matrix
    Sometimes, while working with Python Tuple Matrix, we can have a problem in which we need to get the frequency of each element in it. This kind of problem can occur in domains such as day-day programming and web development domains. Let's discuss certain ways in which this problem can be solved. Inp
    5 min read
  • Python | Frequency grouping of list elements
    Sometimes, while working with lists, we can have a problem in which we need to group element along with it's frequency in form of list of tuple. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is a brute force method to perform this particular task. In this
    6 min read
  • Python | Elements with Frequency equal K
    This is one of the most essential operation that programmer quite often comes in terms with. Be it development or competitive programming, this utility is quite essential to master as it helps to perform many tasks that involve this task to be its subtask. Lets discuss approach to achieve this opera
    3 min read
  • Python | Extract least frequency element
    Sometimes, while working with data, we can have a problem in which we need to extract element which is occurring least number of times in the list. Let's discuss certain ways in which this problem can be solved. Method #1: Using defaultdict() + loop The combination of above functions can be used to
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences