Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Count unique sublists within list in Python
A Python list can contain sublists, which are lists nested within a larger list. In this article we will explore how to count the number of unique sublists within a given list using two different approaches.
Using Counter
Counter is a subclass of Dictionary used to keep track of elements and their count. It stores elements as dictionary keys and their count as dictionary values. To count sublists, we convert each sublist to a string representation ?
Example
from collections import Counter
# Given List with sublists
days_list = [['Mon'], ['Tue', 'Wed'], ['Tue', 'Wed']]
print("Original list:", days_list)
# Count unique sublists by converting to strings
result = Counter(str(elem) for elem in days_list)
print("Count using Counter:", result)
Original list: [['Mon'], ['Tue', 'Wed'], ['Tue', 'Wed']]
Count using Counter: Counter({"['Tue', 'Wed']": 2, "['Mon']": 1})
Using Dictionary with Tuples
We can iterate through the list elements, convert each sublist to a tuple (since tuples are hashable), and count occurrences manually. This approach gives us more control over the counting process ?
Example
# Given List with sublists
days_list = [['Mon'], ['Tue', 'Wed'], ['Tue', 'Wed'], ['Tue', 'Wed']]
print("Original list:", days_list)
# Initialize dictionary
count_dict = {}
# Count occurrences using tuples as keys
for sublist in days_list:
tuple_key = tuple(sublist)
count_dict[tuple_key] = count_dict.get(tuple_key, 0) + 1
print("Count using dictionary:", count_dict)
Original list: [['Mon'], ['Tue', 'Wed'], ['Tue', 'Wed'], ['Tue', 'Wed']]
Count using dictionary: {('Mon',): 1, ('Tue', 'Wed'): 3}
Comparison
| Method | Key Type | Best For |
|---|---|---|
| Counter with strings | String representation | Quick one−liner solution |
| Dictionary with tuples | Tuple (hashable) | Better performance and cleaner output |
Conclusion
Use Counter with string conversion for quick counting, or use dictionary with tuples for better performance. Both methods effectively count unique sublists, with tuples being more memory−efficient than string representations.
