Python | Counting the occurrence of tuples in a list of tuples



Here are some ways to achieve the above objective.

Method # 1: Using Iteration

# Python code for counting uniqueness
# tuples in the list

 

import collections 

Output = collections.defaultdict ( int )

  
# Initialization list

Input = [[( ` hi` , `bye`  )], [( `Geeks` , ` forGeeks` )],

[( `a` , ` b` )], [( ` hi` , `bye` )], [( `a` , `b` )]]

  
# Using iteration

for elem in Input :

Output [elem [ 0 ]] + = 1

 
# Printout

print (Output)

Exit:

 defaultdict (& lt; class `int` & gt ;, {(` Geeks`, `forGeeks`): 1, (` hi`, `bye`): 2, (`a`,` b`): 2}) 

Method # 2: Using chain and Counter

# Python code for counting uniqueness
# tuples in the list

 
# Import

from collections import  Counter

from itertools import chain

 
# Initialization list

Input = [[( `hi` , ` bye` )], [( ` Geeks` , `forGeeks` )],

[( `a` , ` b` )], [( `hi` , ` bye` )], [( `a` , `b` )]]

 
# Using counter and chaining

Output = Counter (chain ( * Input ))

  
# Printout

print (Output)

Exit:

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