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:
How to Get the Number of Elements in a Python List
Next article icon

Python – Find the frequency of numbers greater than each element in a list

Last Updated : 20 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list, a new list is constructed that has frequency of elements greater than or equal to it, corresponding to each element of the list.

Input : test_list = [6, 3, 7, 1, 2, 4] 
Output : [2, 4, 1, 6, 5, 3] 
Explanation : 6, 7 are greater or equal to 6 in list, hence 2.

Input : test_list = [6, 3, 7] 
Output : [2, 3, 1] 
Explanation : 6, 7 are greater or equal to 6 in list, hence 2. 

Method 1 : Using sum() and list comprehension

Here, nested list comprehension is used to access each element of the list and sum() is used to get summation of elements which are greater than or equal to the indexed element. 

Python3




# initializing list
test_list = [6, 3, 7, 1, 2, 4]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sum() performs counts of element which are Greater or equal to
res = [sum(1 for ele in test_list if sub <= ele) for sub in test_list]
     
# printing result
print("Greater elements Frequency list : " + str(res))
 
 
Output
The original list is : [6, 3, 7, 1, 2, 4] Greater elements Frequency list : [2, 4, 1, 6, 5, 3] 

Time Complexity: O(n), where n is the length of the input list. This is because we’re using the built-in sum() and list comprehension which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), as we’re not using additional space 

Method 2 : Using sorted(), bisect_left() and list comprehension

In this, we get elements smaller than the element using bisect_left(). Then, subtracting the number so obtained from total length gives us count of elements greater than element.
 

Python3




# import module
import bisect
 
# initializing list
test_list = [6, 3, 7, 1, 2, 4]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sorting before bisect
temp = sorted(test_list)
 
# getting total greater elements for each element
res = [len(test_list) - bisect.bisect_left(temp, ele) for ele in test_list]
     
# printing result
print("Greater elements Frequency list : " + str(res))
 
 
Output
The original list is : [6, 3, 7, 1, 2, 4] Greater elements Frequency list : [2, 4, 1, 6, 5, 3] 

Method 3:Using a for loop and if statement

Python3




# initializing list
test_list = [6, 3, 7, 1, 2, 4]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using for loop and if statement
res = []
for sub in test_list:
    count = 0
    for ele in test_list:
        if sub <= ele:
            count += 1
    res.append(count)
 
# printing result
print("Greater elements Frequency list : " + str(res))
#This code is contributed by Vinay Pinjala.
 
 
Output
The original list is : [6, 3, 7, 1, 2, 4] Greater elements Frequency list : [2, 4, 1, 6, 5, 3] 

Time complexity: O(n)
Auxiliary Space: O(n)

Method 4: Approach using a dictionary

Python3




# Initialize the list of numbers
test_list = [6, 3, 7, 1, 2, 4]
 
# Print the original list
print("The original list is : " + str(test_list))
 
# Initialize an empty dictionary to store the count of elements greater than or equal to each element
counts = {}
 
# Loop through each element in the list
for i in test_list:
    # Calculate the count of elements greater than or equal to the current element
    counts[i] = len([j for j in test_list if j >= i])
 
# Construct the final result list using the values in the counts dictionary
result = [counts[i] for i in test_list]
 
# Print the final result list
print("Greater elements Frequency list : " + str(result))
 
 
Output
The original list is : [6, 3, 7, 1, 2, 4] Greater elements Frequency list : [2, 4, 1, 6, 5, 3] 

Step-by-step algorithm:

  1. Initialize the list of numbers test_list with the given input.
  2. Initialize an empty dictionary counts to store the count of elements greater than or equal to each element.
  3. Loop through each element in the list using a for loop.
  4. Inside the loop, calculate the count of elements greater than or equal to the current element by using a list comprehension. The list comprehension creates a new list of all elements in test_list that are greater than or equal to the current element i, and the len() function is used to count the number of elements in the list.
  5. Add an entry to the counts dictionary for the current element i, with the count calculated in step 4 as the value.
  6. Construct the final result list by using a list comprehension to extract the count for each element in test_list from the counts dictionary.
  7. Print the final result list.

Time complexity:
The time complexity of the algorithm is O(n^2), where n is the length of the input list test_list. This is because the algorithm loops through each element in the list, and for each element, it loops through the entire list again to count the number of elements greater than or equal to the current element. Therefore, the total number of operations performed is proportional to n*n.

Auxiliary space complexity:
The auxiliary space complexity of the algorithm is O(n), where n is the length of the input list test_list. This is because the counts dictionary stores an entry for each element in the input list, and the size of the dictionary is proportional to n. The final result list also has n elements, so the space complexity of the algorithm is linear with respect to the length of the input list.

Method 5: Using recursion:

Algorithm:

1.We define a recursive function count_greater_or_equal_elements that takes in the list test_list, dictionaries counts, result, and integer i as parameters.
2.The function first checks if i is equal to the length of test_list. If it is, the function returns result.
3.Otherwise, the function calculates the count of elements greater than or equal to the current element current_element at index i in test_list.
4.The function stores this count in the counts dictionary with the current_element as key and count as value.
5.The function appends the count to the result list.
6.The function then recursively calls itself with the updated counts, result, and i values.

Python3




def count_greater_or_equal_elements(test_list, counts={}, result=[], i=0):
    # Base case: If all elements in the list have been processed, return the final result
    if i == len(test_list):
        return result
     
    # Recursive case: Calculate the count of elements greater than or equal to the current element
    current_element = test_list[i]
    count = len([j for j in test_list if j >= current_element])
    counts[current_element] = count
     
    # Add the count to the result list
    result.append(count)
     
    # Recursively process the rest of the list
    return count_greater_or_equal_elements(test_list, counts, result, i+1)
     
# Initialize the list of numbers
test_list = [6, 3, 7, 1, 2, 4]
 
# Print the original list
print("The original list is : " + str(test_list))
 
# Call the recursive function to calculate the count of elements greater than or equal to each element
result = count_greater_or_equal_elements(test_list)
 
# Print the final result list
print("Greater elements Frequency list : " + str(result))
 
#This code is contributed by Jyothi pinjala.
 
 
Output
The original list is : [6, 3, 7, 1, 2, 4] Greater elements Frequency list : [2, 4, 1, 6, 5, 3] 

Time complexity:

The time complexity of the algorithm is O(n^2), where n is the length of the input list.
This is because for each element in the list, we need to compare it to every other element in the list to determine the count of elements greater than or equal to it. This results in a nested loop structure, giving a time complexity of O(n^2).
Auxiliary Space:

The space complexity of the algorithm is O(n), where n is the length of the input list.
This is because we need to create a dictionary counts with n key-value pairs to store the count of elements greater than or equal to each element in the list. We also need to create a list result of size n to store the result. Additionally, we use recursion which results in n function call stack frames. Therefore, the total space complexity is O(n).

Method 6: Using numpy

Step-by-step approach:

  • Initialize an empty list “result” to store the frequency of greater elements for each element in the input list.
  • Convert the input list “test_list” into a NumPy array.
  • Loop through each element “x” in the input list “test_list“.
  • Create a boolean NumPy array by comparing each element in the NumPy array with “x“.
  • Calculate the sum of the boolean array using the NumPy “np.sum()” function to count the number of elements greater than or equal to “x“.
  • Append the result to the “result” list.
  • Return the “result” list.

Python3




import numpy as np
 
test_list = [6, 3, 7, 1, 2, 4]
print("The original list is : " + str(test_list))
 
result = [np.sum(np.array(test_list) >= x) for x in test_list]
 
print("Greater elements Frequency list : " + str(result))
 
 

Output

The original list is : [6, 3, 7, 1, 2, 4] Greater elements Frequency list : [2, 4, 1, 6, 5, 3]

Time complexity: O(n^2) due to the nested loops in calculating the frequency for each element in the input list. 
Auxiliary space: O(n) to store the “result” list.



Next Article
How to Get the Number of Elements in a Python List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Find sum of frequency of given elements in the list
    Given two lists containing integers, the task is to find the sum of the frequency of elements of the first list in the second list. Example: Input: list1 = [1, 2, 3] list2 = [2, 1, 2, 1, 3, 5, 2, 3] Output: 7 Explanation: No of time 1 occurring in list2 is :2 No of time 2 occurring in list2 is :3 No
    4 min read
  • Python | Find most frequent element in a list
    Given a list, find the most frequent element in it. If multiple elements appear a maximum number of times, print any one of them using Python. Example Make a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we
    2 min read
  • How to Get the Number of Elements in a Python List
    In Python, lists are one of the most commonly used data structures to store an ordered collection of items. In this article, we'll learn how to find the number of elements in a given list with different methods. Example Input: [1, 2, 3.5, geeks, for, geeks, -11]Output: 7 Let's explore various ways t
    3 min read
  • Python | Find top K frequent elements from a list of tuples
    Given a list of tuples with word as first element and its frequency as second element, the task is to find top k frequent element. Below are some ways to above achieve the above task. Method #1: Using defaultdict C/C++ Code # Python code to find top 'k' frequent element # Importing import collection
    5 min read
  • Python program to print Rows where all its Elements' frequency is greater than K
    Given Matrix, extract all rows whose all elements have a frequency greater than K. Input : test_list = [[1, 1, 2, 3, 2, 3], [4, 4, 5, 6, 6], [1, 1, 1, 1], [4, 5, 6, 8]], K = 2 Output : [[1, 1, 1, 1]] Explanation : Here, frequency of 1 is 4 > 2, hence row retained. Input : test_list = [[1, 1, 2, 3
    8 min read
  • Python | Get the Index of first element greater than K
    Python list operations are always desired to have shorthands as they are used in many places in development. Hence having knowledge of them always remains quite useful. Let's deals with finding one such utility of having index of first element greater than K by one-liner. There are various ways in w
    6 min read
  • Python - Extract elements with Frequency greater than K
    Given a List, extract all elements whose frequency is greater than K. Input : test_list = [4, 6, 4, 3, 3, 4, 3, 4, 3, 8], K = 3 Output : [4, 3] Explanation : Both elements occur 4 times. Input : test_list = [4, 6, 4, 3, 3, 4, 3, 4, 6, 6], K = 2 Output : [4, 3, 6] Explanation : Occur 4, 3, and 3 time
    7 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 - Fractional Frequency of elements in List
    Given a List, get fractional frequency of each element at each position. Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 4] Output : ['1/4', '1/3', '2/4', '1/1', '1/1', '2/3', '3/4', '3/3', '4/4'] Explanation : 4 occurs 1/4th of total occurrences till 1st index, and so on.Input : test_list = [4, 5, 4,
    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
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