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:
Prefix frequency in string List - Python
Next article icon

Python - List Words Frequency in String

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a List of Words, Map frequency of each to occurrence in String.

Input : test_str = 'geeksforgeeks is best for geeks and best for CS', count_list = ['best', 'geeksforgeeks', 'computer']  Output : [2, 1, 0]  Explanation : best has 2 occ., geeksforgeeks 1 and computer is not present in string.
Input : test_str = 'geeksforgeeks is best for geeks and best for CS', count_list = ['better', 'gfg', 'computer']  Output : [0, 0, 0]  Explanation : No word from list present in string.

Method #1 : Using defaultdict() + loop + list comprehension

In this, we compute words frequency using loop + defaultdict() and then use list comprehension to get all the counts corresponding to list of words.

Python3
# Python3 code to demonstrate working of # Divide String into Equal K chunks # Using list comprehension from collections import defaultdict  # Initializing strings test_str = 'geeksforgeeks is best for geeks and best for CS'  # Printing original string print("The original string is : " + str(test_str))  # Initializing count_list count_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and']  # Computing frequency res = defaultdict(int)  for sub in test_str.split():     res[sub] += 1  # Assigning to list words res = [res[sub] for sub in count_list]  # Printing result print("The list words frequency : " + str(res)) 

Output
The original string is : geeksforgeeks is best for geeks and best for CS The list words frequency : [2, 1, 0, 0, 2, 1]

Time Complexity: O(n)
Auxiliary Space: O(n), where n is the length of the list.

Method #2 : Using Counter() + list comprehension

In this, Counter() is used to perform the task of computing frequency, post that, list comprehension is used to assign a frequency to list words.

Python3
# Python3 code to demonstrate working of  # Divide String into Equal K chunks # Using list comprehension from collections import Counter  # initializing strings test_str = 'geeksforgeeks is best for geeks and best for CS'  # printing original string print("The original string is : " + str(test_str))  # initializing count_list  count_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and']  # computing frequency using Counter() res = Counter(test_str.split())      # assigning to list words res = [res[sub] for sub in count_list]  # printing result  print("The list words frequency : " + str(res))  

Output
The original string is : geeksforgeeks is best for geeks and best for CS The list words frequency : [2, 1, 0, 0, 2, 1]

Time complexity: O(N) since using a loop
Auxiliary Space: O(1)

Method #3 : Using count() method

Approach

  1. Split the string test_str which results in a list(x)
  2. Initiate a for loop to traverse the list of strings.
  3. Now append the occurrence of each string in x to the output list.
  4. Display output list.
Python3
# Python3 code to demonstrate working of # Divide String into Equal K chunks  # Initializing strings test_str = 'geeksforgeeks is best for geeks and best for CS'  # Printing original string print("The original string is : " + str(test_str)) x=test_str.split()  # Iitializing count_list count_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and']  # Cmputing frequency res=[]  for i in count_list:     res.append(x.count(i))  # Pinting result print("The list words frequency : " + str(res)) 

Output
The original string is : geeksforgeeks is best for geeks and best for CS The list words frequency : [2, 1, 0, 0, 2, 1]

Time Complexity : O(M*N) M - length of x N - length of count_list
Auxiliary Space : O(N) N - length of output list

Method #4: Using dictionary comprehension

In this method, we can use a dictionary comprehension to count the frequency of each word in the given string. The keys of the dictionary will be the words from the count_list, and the values will be the frequency of each word in the given string. 

Python3
# Python3 code to demonstrate working of # Divide String into Equal K chunks   # initializing strings test_str = 'geeksforgeeks is best for geeks and best for CS'  # printing original string print("The original string is : " + str(test_str))  # initializing count_list count_list = ['best', 'geeksforgeeks', 'computer', 'better', 'for', 'and']  # computing frequency using dictionary comprehension res = {i: test_str.split().count(i) for i in count_list}  # printing result print("The list words frequency : " + str([res[i] for i in count_list])) 

Output
The original string is : geeksforgeeks is best for geeks and best for CS The list words frequency : [2, 1, 0, 0, 2, 1]

Time complexity: O(N), where n is the length of the given string.
Auxiliary space: O(K), where k is the number of words in the count_list.


Next Article
Prefix frequency in string List - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - List Strings frequency in Matrix
    Sometimes, while working with Matrix, we can have a problem in which we need to check the frequency of argument Strings from List in each row of Matrix. This is a very peculiar problem and can have usefulness in many domains. Let us discuss certain ways in which this task can be solved. Method #1 :
    5 min read
  • Prefix frequency in string List - Python
    In this article, we will explore various methods to find prefix frequency in string List. The simplest way to do is by using a loop. Using a LoopOne of the simplest ways to calculate the frequency of a prefix in a list of strings is by iterating through each element and checking if the string starts
    2 min read
  • Most Frequent Word in Strings List
    We are given a list of strings we need to find the most frequent words from that particular list. For example, w = ["apple", "banana", "apple", "orange", "banana", "apple"] we need to find most frequent words in list which is 'apple' in this case. Using Counter from collectionsCounter class from the
    2 min read
  • Python | Extract Nth words in Strings List
    Sometimes, while working with Python Lists, we can have problems in which we need to perform the task of extracting Nth word of each string in List. This can have applications in the web-development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using list compreh
    7 min read
  • Frequency of Numbers in String - Python
    We are given a string and we have to determine how many numeric characters (digits) are present in the given string. For example: "Hello123World456" has 6 numeric characters (1, 2, 3, 4, 5, 6). Using re.findall() re.findall() function from the re module is a powerful tool that can be used to match s
    3 min read
  • Python - Words Lengths in String
    We are given a string we need to find length of each word in a given string. For example, we are s = "Hello world this is Python" we need to find length of each word so that output should be a list containing length of each words in sentence, so output in this case will be [5, 5, 4, 2, 6]. Using Lis
    2 min read
  • Python - Get Nth word in given String
    Sometimes, while working with data, we can have a problem in which we need to get the Nth word of a String. This kind of problem has many application in school and day-day programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop This is one way in which thi
    4 min read
  • Python - All substrings Frequency in String
    Given a String, extract all unique substrings with their frequency. Input : test_str = "ababa" Output : {'a': 3, 'ab': 2, 'aba': 2, 'abab': 1, 'ababa': 1, 'b': 2, 'ba': 2, 'bab': 1, 'baba': 1} Explanation : All substrings with their frequency extracted. Input : test_str = "GFGF" Output : {'G': 2, 'G
    5 min read
  • Python | Frequency of substring in given string
    Finding a substring in a string has been dealt with in many ways. But sometimes, we are just interested to know how many times a particular substring occurs in a string. Let's discuss certain ways in which this task is performed. Method #1: Using count() This is a quite straightforward method in whi
    6 min read
  • Python - Bigrams Frequency in String
    Sometimes while working with Python Data, we can have problem in which we need to extract bigrams from string. This has application in NLP domains. But sometimes, we need to compute the frequency of unique bigram for data collection. The solution to this problem can be useful. Lets discuss certain w
    4 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