- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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}
- Related Articles
- Program to count number of sublists with exactly k unique elements in Python
- Count the sublists containing given element in a list in Python
- Python - Unique keys count for Value in Tuple List
- Python program to unique keys count for Value in Tuple List
- Python program to print all sublists of a list.
- Count unique values per groups in Python Pandas
- Python - Unique values count of each Key
- Get unique values from a list in Python
- Assign value to unique number in list in Python
- Adding value to sublists in Python
- Program to find number of sublists with sum k in a binary list in Python
- Check if list contains all unique elements in Python
- How to remove unique characters within strings in R?
- Python – Average digits count in a List
- Assign ids to each unique value in a Python list
