
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Count tuples occurrence in list of tuples in Python
A list is made up of tuples as its element. In this article we will count the number of unique tuples present in the list.
With defaultdict
We treat the given list as a defaultdict data container and count the elements in it using the in condition.
Example
import collections Alist = [[('Mon', 'Wed')], [('Mon')], [('Tue')],[('Mon', 'Wed')] ] # Given list print("Given list:\n", Alist) res = collections.defaultdict(int) for elem in Alist: res[elem[0]] += 1 print("Count of tuples present in the list:\n",res)
Output
Running the above code gives us the following result −
Given list: [[('Mon', 'Wed')], ['Mon'], ['Tue'], [('Mon', 'Wed')]] Count of tuples present in the list: defaultdict(, {('Mon', 'Wed'): 2, 'Mon': 1, 'Tue': 1})
With Counter and chain
The counter and chain functions are part of collections and itertools modules. Using them together we can get the count of each element in the list which are tuples.
Example
from collections import Counter from itertools import chain Alist = [[('Mon', 'Wed')], [('Mon')], [('Tue')],[('Mon', 'Wed')] ] # Given list print("Given list:\n", Alist) res = Counter(chain(*Alist)) print("Count of tuples present in the list:\n",res)
Output
Running the above code gives us the following result −
Given list: [[('Mon', 'Wed')], ['Mon'], ['Tue'], [('Mon', 'Wed')]] Count of tuples present in the list: Counter({('Mon', 'Wed'): 2, 'Mon': 1, 'Tue': 1})
- Related Articles
- Combining tuples in list of tuples in Python
- Remove duplicate tuples from list of tuples in Python
- Summation of tuples in list in Python
- Remove tuples from list of tuples if greater than n in Python
- Python program to find Tuples with positive elements in List of tuples
- Convert list of tuples into list in Python
- Remove tuples having duplicate first value from given list of tuples in Python
- Python program to find Tuples with positive elements in a List of tuples
- Convert list of tuples to list of list in Python
- Finding frequency in list of tuples in Python
- Custom sorting in list of tuples in Python
- Find the tuples containing the given element from a list of tuples in Python
- List of tuples to dictionary conversion in Python
- Convert list of tuples into digits in Python
- Convert dictionary to list of tuples in Python

Advertisements