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:
Frequency of Numbers in String - Python
Next article icon

Python – List Strings frequency in Matrix

Last Updated : 26 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 : Using count() + loop

The combination of the above functionalities can be used to perform this task. In this we count the frequency using count() and the task of iteration is performed inside the loop.

Python3




# Python3 code to demonstrate
# List Strings frequency in Matrix
# using count() + loop
 
# Initializing lists
test_list1 = [['Gfg', 'is', 'best'], ['Gfg', 'is',
                                      'for', 'CS'], ['Gfg', 'is', 'for', 'Geeks']]
test_list2 = ['Gfg', 'is', 'best']
 
# printing original list1
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# List Strings frequency in Matrix
# using count() + loop
res = []
for val in test_list1:
    res.append([val.count(ele) for ele in test_list2])
 
# printing result
print("Frequency of strings in Matrix : " + str(res))
 
 
Output : 
The original list 1 is : [['Gfg', 'is', 'best'], ['Gfg', 'is', 'for', 'CS'], ['Gfg', 'is', 'for', 'Geeks']] The original list 2 is : ['Gfg', 'is', 'best'] Frequency of strings in Matrix : [[1, 1, 1], [1, 1, 0], [1, 1, 0]]

Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a list with m * n keys and a list of m * n elements

Method #2: Using list comprehension 

This is yet another way in which this task can be performed. This is shortened version of the above methodone-lineriner. 

Python3




# Python3 code to demonstrate
# List Strings frequency in Matrix
# using list comprehension
 
# Initializing lists
test_list1 = [['Gfg', 'is', 'best'], ['Gfg', 'is',
              'for', 'CS'], ['Gfg', 'is', 'for', 'Geeks']]
test_list2 = ['Gfg', 'is', 'best']
 
# printing original list1
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# List Strings frequency in Matrix
# using list comprehension
res = [[sub.count(ele) for ele in test_list2] for sub in test_list1]
 
# printing result
print("Frequency of strings in Matrix : " + str(res))
 
 
Output : 
The original list 1 is : [['Gfg', 'is', 'best'], ['Gfg', 'is', 'for', 'CS'], ['Gfg', 'is', 'for', 'Geeks']] The original list 2 is : ['Gfg', 'is', 'best'] Frequency of strings in Matrix : [[1, 1, 1], [1, 1, 0], [1, 1, 0]]

Method #3: Using operator.countOf() + loop 

The combination of the above functionalities can be used to perform this task. In this we count the frequency using count() and task of iteration is performed inside the loop.

Python3




# Python3 code to demonstrate
# List Strings frequency in Matrix
# using operator.countOf() + loop
import operator as op
 
# Initializing lists
test_list1 = [['Gfg', 'is', 'best'], ['Gfg', 'is',
    'for', 'CS'], ['Gfg', 'is', 'for', 'Geeks']]
test_list2 = ['Gfg', 'is', 'best']
 
# printing original list1
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# List Strings frequency in Matrix
# using operator.countOf() + loop
res = []
for val in test_list1:
    res.append([op.countOf(val, ele) for ele in test_list2])
 
# printing result
print("Frequency of strings in Matrix : " + str(res))
 
 
Output
The original list 1 is : [['Gfg', 'is', 'best'], ['Gfg', 'is', 'for', 'CS'], ['Gfg', 'is', 'for', 'Geeks']] The original list 2 is : ['Gfg', 'is', 'best'] Frequency of strings in Matrix : [[1, 1, 1], [1, 1, 0], [1, 1, 0]]

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

Method 4: Using a dictionary

Approach:

  1. Initialize an empty dictionary to store the frequency of each string in the matrix.
  2. Loop through each sublist in the matrix.
  3. Loop through each string in the sublist.
  4. Check if the string exists in the dictionary.
  5. If the string exists in the dictionary, increment its count by 1. Otherwise, add the string to the dictionary with a count of 1.
  6. Return the dictionary.

Python3




# Initializing lists
test_list1 = [['Gfg', 'is', 'best'], ['Gfg', 'is',
                                      'for', 'CS'], ['Gfg', 'is', 'for', 'Geeks']]
test_list2 = ['Gfg', 'is', 'best']
 
# Define a function to count the frequency of strings in the matrix
 
 
def count_strings_freq(matrix, strings):
   
   
    res = []
     
    for sublist in matrix:
       
        # initial frequency is set to null
        freq_list = []
        for string in strings:
            freq_list.append(sublist.count(string))
             
        # Appending into result    
        res.append(freq_list)
     
    return res
 
 
# Call the function with the input lists
res = count_strings_freq(test_list1, test_list2)
 
# printing result
print("Frequency of strings in Matrix : " + str(res))
 
 
Output
Frequency of strings in Matrix : [[1, 1, 1], [1, 1, 0], [1, 1, 0]]

Time complexity: O(n*m), where n is the number of sublists in the matrix and m is the total number of strings in all sublists.
Auxiliary space: O(k), where k is the number of unique strings in the matrix.



Next Article
Frequency of Numbers in String - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • 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
  • Python - List Words Frequency in String
    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
    4 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
  • Create a List of Strings in Python
    Creating a list of strings in Python is easy and helps in managing collections of text. For example, if we have names of people in a group, we can store them in a list. We can create a list of strings by using Square Brackets [] . We just need to type the strings inside the brackets and separate the
    3 min read
  • Python - Frequency of K in sliced String
    Given a String, find the frequency of certain characters in the index range. Input : test_str = 'geeksforgeeks is best for geeks', i = 3, j = 9, K = 'e' Output : 0 Explanation : No occurrence of 'e' between 4th [s] and 9th element Input : test_str = 'geeksforgeeks is best for geeks', i = 0, j = 9, K
    6 min read
  • Python - Formable Strings Count in Matrix
    Given strings matrix, the task is to write a Python program to count strings that can be made from letters from the given list. Examples: Input : test_list = [["gfg", "best"], ["all", "love", "gfg"], ["gfg", "is", "good"], ["geeksforgeeks"]], tar_list = ["g", "f", "s", "b", "o", "d", "e", "t"] Outpu
    5 min read
  • Maximum Frequency Character in String - Python
    The task of finding the maximum frequency character in a string involves identifying the character that appears the most number of times. For example, in the string "hello world", the character 'l' appears the most frequently (3 times). Using collection.CounterCounter class from the collections modu
    3 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 - Values Frequency Index List
    Sometimes, while working with Python tuples, we can have a problem in which we need to extract the frequency of each value in tuple. This has been solved earlier. We can have a modification in which we need to create list in which index represents the key and value of it represents the frequency of
    4 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
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