Python | Count tuples occurrence in list of tuples

Many a time while developing web and desktop product in Python, we use nested lists and have several queries about how to find count of unique tuples. Let’s see how to get count of unique tuples in given list of tuples.

Below are some ways to achieve the above task.

Method #1: Using Iteration

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to count unique 
# tuples in list of list
  
import collections 
Output = collections.defaultdict(int)
  
# List initialization
Input = [[('hi', 'bye')], [('Geeks', 'forGeeks')],
         [('a', 'b')], [('hi', 'bye')], [('a', 'b')]]
  
# Using iteration
for elem in Input:
      Output[elem[0]] += 1
      
# Printing output
print(Output)

chevron_right


Output:

defaultdict(<class 'int'>, {('Geeks', 'forGeeks'): 1, ('hi', 'bye'): 2, ('a', 'b'): 2})

 

Method #2: Using chain and Counter

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to count unique 
# tuples in list of list
  
# Importing
from collections import Counter
from itertools import chain
  
# List initialization
Input = [[('hi', 'bye')], [('Geeks', 'forGeeks')],
         [('a', 'b')], [('hi', 'bye')], [('a', 'b')]]
  
# Using counter and chain
Output = Counter(chain(*Input))
  
# Printing output
print(Output)

chevron_right


Output:

Counter({('hi', 'bye'): 2, ('a', 'b'): 2, ('Geeks', 'forGeeks'): 1})


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.