Count tuples occurrence in list of tuples in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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})
raja
Published on 04-Jun-2020 11:38:09
Advertisements