Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Count tuples occurrence in list of tuples in Python
A list is made up of tuples as its elements. In this article we will count the number of unique tuples present in the list and their occurrences using different approaches.
Using defaultdict
We treat the given list as a defaultdict data container and count the elements in it using iteration. The defaultdict automatically initializes missing keys with a default value.
Example
import collections
tuple_list = [('Mon', 'Wed'), ('Mon',), ('Tue',), ('Mon', 'Wed')]
# Given list
print("Given list:", tuple_list)
res = collections.defaultdict(int)
for elem in tuple_list:
res[elem] += 1
print("Count of tuples present in the list:")
print(dict(res))
Given list: [('Mon', 'Wed'), ('Mon',), ('Tue',), ('Mon', 'Wed')]
Count of tuples present in the list:
{('Mon', 'Wed'): 2, ('Mon',): 1, ('Tue',): 1}
Using Counter
The Counter class from the collections module provides a convenient way to count hashable objects. It returns a dictionary subclass with counts as values.
Example
from collections import Counter
tuple_list = [('Mon', 'Wed'), ('Mon',), ('Tue',), ('Mon', 'Wed')]
# Given list
print("Given list:", tuple_list)
res = Counter(tuple_list)
print("Count of tuples present in the list:")
print(dict(res))
Given list: [('Mon', 'Wed'), ('Mon',), ('Tue',), ('Mon', 'Wed')]
Count of tuples present in the list:
{('Mon', 'Wed'): 2, ('Mon',): 1, ('Tue',): 1}
Using Dictionary Comprehension
We can also use dictionary comprehension with the count() method to achieve the same result in a more compact way.
Example
tuple_list = [('Mon', 'Wed'), ('Mon',), ('Tue',), ('Mon', 'Wed')]
# Given list
print("Given list:", tuple_list)
# Count unique tuples
unique_tuples = set(tuple_list)
res = {t: tuple_list.count(t) for t in unique_tuples}
print("Count of tuples present in the list:")
print(res)
Given list: [('Mon', 'Wed'), ('Mon',), ('Tue',), ('Mon', 'Wed')]
Count of tuples present in the list:
{('Tue',): 1, ('Mon',): 1, ('Mon', 'Wed'): 2}
Comparison
| Method | Performance | Best For |
|---|---|---|
defaultdict |
Good | Manual control over counting logic |
Counter |
Best | Most readable and Pythonic |
| Dictionary comprehension | Poor for large lists | Small lists, educational purposes |
Conclusion
Use Counter for the most Pythonic and efficient approach to count tuple occurrences. The defaultdict method provides more control, while dictionary comprehension is suitable for small datasets.
