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 - Elements Frequency in Mixed Nested Tuple
Next article icon

Python - Elements frequency in Tuple Matrix

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

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.

Input : test_list = [[(4, 5), (3, 2)], [(2, 2)]] 
Output : {4: 1, 5: 1, 3: 1, 2: 3}

Input : test_list = [[(4, 5), (3, 2)]] 
Output : {4: 1, 5: 1, 3: 1, 2: 1} 


Method #1 : Using nested chain() + "*" operator + Counter() 

The combination of the above functions can be used to solve this problem. In this, we perform the task of getting frequency using Counter() and nested chain to cater the nestings, and the "*" operator is used to perform unpacking and packing of each element. 

Python3
# Python3 code to demonstrate working of # Elements frequency in Tuple Matrix # Using nested chain() + "*" operator + Counter() from itertools import chain from collections import Counter  # initializing lists test_list = [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]  # printing original list print("The original list is : " + str(test_list))  # Elements frequency in Tuple Matrix # Using nested chain() + "*" operator + Counter() res = dict(Counter(chain(*chain(*test_list))))  # printing result print("Elements frequency : " + str(res)) 

Output : 
The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]] Elements frequency : {4: 1, 5: 3, 3: 1, 2: 4, 1: 1}

 

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 dictionary with m * n keys and a list of m * n elements

 Method #2: Using chain.from_iterables() + Counter() 

The combination of the above functions can be used to solve this problem. In this, we perform the task of packing, unpacking, and flattening using chain.from_iterables(). 

Python3
# Python3 code to demonstrate working of # Elements frequency in Tuple Matrix # Using chain.from_iterables() + Counter() from itertools import chain from collections import Counter  # initializing lists test_list = [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]  # printing original list print("The original list is : " + str(test_list))  # Elements frequency in Tuple Matrix # Using chain.from_iterables() + Counter() res = dict(Counter(chain.from_iterable(chain.from_iterable(test_list))))  # printing result print("Elements frequency : " + str(res)) 

Output : 
The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]] Elements frequency : {4: 1, 5: 3, 3: 1, 2: 4, 1: 1}

 

Time Complexity: O(n^2), where n is the total number of tuples in the input "test_list".
Auxiliary Space: O(n)

Method #3 : Using extend() and count() methods

Approach

  1. Converted the tuple matrix to list using nested for loops and extend() method
  2. Created a new list with unique elements of above list
  3. Initiated a for loop to create a dictionary with key as unique element and value as it's count
  4. Displayed the dictionary
Python3
# Python3 code to demonstrate working of # Elements frequency in Tuple Matrix  # initializing lists test_list = [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]  # printing original list print("The original list is : " + str(test_list))  # Elements frequency in Tuple Matrix res = dict() x = [] for i in test_list:     for j in i:         x.extend(list(j)) y = list(set(x)) for i in y:     res[i] = x.count(i) # printing result print("Elements frequency : " + str(res)) 

Output
The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]] Elements frequency : {1: 1, 2: 4, 3: 1, 4: 1, 5: 3}

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

Method #4 : Using extend() and operator.countOf() methods

Approach

  1. Converted the tuple matrix to list using nested for loops and extend() method
  2. Created a new list with unique elements of above list
  3. Initiated a for loop to create a dictionary with key as unique element and value as it's count(using operator.countOf())
  4. Displayed the dictionary 
Python3
# Python3 code to demonstrate working of # Elements frequency in Tuple Matrix  # initializing lists import operator test_list = [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]  # printing original list print("The original list is : " + str(test_list))  # Elements frequency in Tuple Matrix res = dict() x = [] for i in test_list:     for j in i:         x.extend(list(j)) y = list(set(x)) for i in y:     res[i] = operator.countOf(x, i) # printing result print("Elements frequency : " + str(res)) 

Output
The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]] Elements frequency : {1: 1, 2: 4, 3: 1, 4: 1, 5: 3}

Time Complexity : O(N*N) N -length of extended list(x)
Auxiliary Space : O(N) N - length of dictionary

Method #5: Using defaultdict()

Step-by-step approach:

  • Import the defaultdict class from the collections module.
  • Initialize an empty defaultdict object with int() as the default value.
  • Iterate over the test_list, accessing each nested tuple.
  • Iterate over each tuple, accessing each element.
  • Increment the count of each element in the defaultdict object.
  • Print the resulting dictionary
Python3
from collections import defaultdict  test_list = [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]] res = defaultdict(int)  for i in test_list:     for j in i:         for k in j:             res[k] += 1  print("Elements frequency : " + str(dict(res))) 

Output
Elements frequency : {4: 1, 5: 3, 3: 1, 2: 4, 1: 1}

Time Complexity: O(n^2), where n is the length of the largest nested tuple in the test_list.
Auxiliary Space: O(m), where m is the number of unique elements in the test_list.


Next Article
Python - Elements Frequency in Mixed Nested Tuple
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • 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 - 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
  • 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 - Maximum frequency in Tuple
    Sometimes, while working with Python tuples, we can have a problem in which we need to find the maximum frequency element in the tuple. Tuple, being quite a popular container, this type of problem is common across the web development domain. Let's discuss certain ways in which this task can be perfo
    5 min read
  • Python - Group Elements in Matrix
    Given a Matrix with two columns, group 2nd column elements on basis of 1st column. Input : test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [2, 9]] Output : {5: [8, 4], 2: [0, 3, 9]} Explanation : 8 and 4 are mapped to 5 in Matrix, all others to 2. Input : test_list = [[2, 8], [2, 0], [2, 4], [2, 3], [2
    6 min read
  • Python | Tuple Column element frequency
    In Python, we need to handle various forms of data and one among them is a list of tuples in which we may have to perform any kind of operation. This particular article discusses the ways of finding the frequency of the Kth element in the list of tuples. Let’s discuss certain ways in which this can
    5 min read
  • Python - Matrix elements Frequencies Counter
    Sometimes, while working with python Matrix, we can have a problem in which we need to find frequencies of all elements in Matrix. This kind of problem can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using Counter() + sum() + map() The
    5 min read
  • 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
  • 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 - Group similar elements into Matrix
    Sometimes, while working with Python Matrix, we can have a problem in which we need to perform grouping of all the elements with are the same. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [1, 3, 4, 4,
    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