Skip to content
Related Articles

Related Articles

Python | Count tuples occurrence in list of tuples

View Discussion
Improve Article
Save Article
  • Last Updated : 19 Sep, 2022
View Discussion
Improve Article
Save Article

Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task.

Method #1: Using Iteration 

Python3




# 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)


Output:

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

Method #2: Using chain and Counter 

Python3




# 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)


Output:

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

Method #3: List Comprehension method

Python3




Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=[i for i in Input if i==check_ele]
print("tuple ('a', 'b') occures",len(x),"times")


Output

tuple ('a', 'b') occures 2 times

Method #4: Using enumerate function

Python3




Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=[i for a,i in enumerate(Input) if i==check_ele]
print("tuple ('a', 'b') occures",len(x),"times")


Output

tuple ('a', 'b') occures 2 times

Method #5: Using lambda function 

Python3




Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=list(filter(lambda i:(i==check_ele),Input))
print("tuple ('a', 'b') occures",len(x),"times")


Output

tuple ('a', 'b') occures 2 times

Method #6: Using only Counter function 

Python3




from collections import Counter
Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
x=Counter(Input)
print("tuple ('a', 'b') occures",x[check_ele],"times")


Output

tuple ('a', 'b') occures 2 times

Method #7: Using countof function

Python3




import operator as op
Input = [('hi', 'bye'),('Geeks', 'forGeeks'),('a', 'b'),('hi', 'bye'),('a', 'b')]
check_ele=('a', 'b')
print(op.countOf(Input,check_ele))


Output

2

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!