
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 Unique Sublists Within List in Python
A Python list can also contain sublist. A sublist itself is a list nested within a bigger list. In this article we will see how to count the number of unique sublists within a given list.
Using Counter
Counter is a subclass of Dictionary and used to keep track of elements and their count. It is also considered as an unordered collection where elements are stored as Dict keys and their count as dict value. So in the below example we directly take a list which has sublists.
Example
from collections import Counter # Given List Alist = [['Mon'],['Tue','Wed'],['Tue','Wed']] print(Counter(str(elem) for elem in Alist))
Output
Running the above code gives us the following result −
Counter({"['Tue', 'Wed']": 2, "['Mon']": 1})
With append()
We can also iterate through the elements of the list and setting it as tuple and then keep adding 1 for each occurrence of the same element. Finally print the new list showing the sublist as key and their count as values.
Example
# Given List Alist = [['Mon'],['Tue','Wed'],['Tue','Wed'], ['Tue','Wed']] # Initialize list NewList = {} # Use Append through Iteration for elem in Alist: NewList.setdefault(tuple(elem), list()).append(1) for k, v in NewList.items(): NewList[k] = sum(v) # Print Result print(NewList)
Output
Running the above code gives us the following result −
{('Mon',): 1, ('Tue', 'Wed'): 3}