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:
Sort List Elements by Frequency - Python
Next article icon

Python - Step Frequency of elements in List

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

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 this task can be performed. 

Method #1 : Using loop + defaultdict() The combination of above functions can be used to perform this task. In this, we just initialize list with a default value and increment its frequency using a loop. 

Python3
# Python3 code to demonstrate  # Step Frequency of elements in List # using loop + defaultdict() from collections import defaultdict  # Initializing loop  test_list = ['gfg', 'is', 'best', 'gfg', 'is', 'life']  # printing original list  print("The original list is : " + str(test_list))  # Step Frequency of elements in List # using loop + defaultdict() res_d = defaultdict(int) res = [] for ele in test_list:     res_d[ele] += 1     res.append(res_d[ele])  # printing result  print ("Step frequency of elements is : " + str(res)) 

Output
The original list is : ['gfg', 'is', 'best', 'gfg', 'is', 'life'] Step frequency of elements is : [1, 1, 1, 2, 2, 1]

Time complexity: O(n), where n is the number of elements in the input list test_list.
Auxiliary space: O(m), where m is the number of unique elements in the input list test_list. The defaultdict data structure is used in the code, which may occupy a space equivalent to the number of unique elements in the input list.

Method #2 : Using list comprehension + enumerate() The combination of above functions can be used to solve this problem. In this we just iterate and store the counter using enumerate(). 

Python3
# Python3 code to demonstrate  # Step Frequency of elements in List # using list comprehension + enumerate() from collections import defaultdict  # Initializing loop  test_list = ['gfg', 'is', 'best', 'gfg', 'is', 'life']  # printing original list  print("The original list is : " + str(test_list))  # Step Frequency of elements in List # using list comprehension + enumerate() res = [test_list[ : idx + 1].count(ele) for (idx, ele) in enumerate(test_list)]  # printing result  print ("Step frequency of elements is : " + str(res)) 
Output : 
The original list is : ['gfg', 'is', 'best', 'gfg', 'is', 'life'] Step frequency of elements is : [1, 1, 1, 2, 2, 1]

Time Complexity: O(n^2)
Auxiliary Space: O(n)

Method #3 : Using for loop + count() method

Python3
# Python3 code to demonstrate # Step Frequency of elements in List  # Initializing loop test_list = ['gfg', 'is', 'best', 'gfg', 'is', 'life']  # printing original list print("The original list is : " + str(test_list))  # Step Frequency of elements in List  res = [] for ele in range(0,len(test_list)):     res.append(test_list[:ele+1].count(test_list[ele]))       # printing result print ("Step frequency of elements is : " + str(res)) 

Output
The original list is : ['gfg', 'is', 'best', 'gfg', 'is', 'life'] Step frequency of elements is : [1, 1, 1, 2, 2, 1]

Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.  
Auxiliary Space: O(n), where n is the number of elements in the new res list 

Method #4 : Using operator.countOf() method

Python3
# Python3 code to demonstrate # Step Frequency of elements in List import operator as op # Initializing loop test_list = ['gfg', 'is', 'best', 'gfg', 'is', 'life']  # printing original list print("The original list is : " + str(test_list))  # Step Frequency of elements in List  res = [] for ele in range(0,len(test_list)):     res.append(op.countOf(test_list[:ele+1],test_list[ele]))       # printing result print ("Step frequency of elements is : " + str(res)) 

Output
The original list is : ['gfg', 'is', 'best', 'gfg', 'is', 'life'] Step frequency of elements is : [1, 1, 1, 2, 2, 1]

Time Complexity: O(N)
Auxiliary Space: O(N)


Next Article
Sort List Elements by Frequency - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
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 | 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 - 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
  • Sort List Elements by Frequency - Python
    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'
    3 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 - 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 | 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 - 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
  • Frequency of Elements from Other List - Python
    We are given a list of elements and another list containing specific values and our task is to count the occurrences of these specific values in the first list "a" and return their frequencies. For example: a = [1, 2, 2, 3, 4, 2, 5, 3, 1], b = [1, 2, 3]. Here b contains the elements whose frequency
    3 min read
  • Python - Elements Frequency in Mixed Nested Tuple
    Sometimes, while working with Python data, we can have a problem in which we have data in the form of nested and non-nested forms inside a single tuple, and we wish to count the element frequency in them. This kind of problem can come in domains such as web development and Data Science. Let's discus
    8 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