
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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})
Advertisements