Skip to content
Related Articles

Related Articles

Python – Elements frequency in Tuple Matrix

View Discussion
Improve Article
Save Article
  • Last Updated : 17 Feb, 2022
View Discussion
Improve Article
Save Article

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}

 

 
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}

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!