Count unique sublists within list in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

# 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}
raja
Published on 09-Sep-2020 12:20:42
Advertisements