Python | Count unique sublists within list
Given a list of lists, the task is to find the count of unique sublists within list.
Examples:
Input: [['Geek', 'for', 'geeks'], ['geeks', 'for'],
['for', 'Geeks', 'geek'], ['Geek', 'for', 'geeks']]
Output:
{('geeks', 'for'): 1, ('for', 'Geeks', 'geek'): 1,
('Geek', 'for', 'geeks'): 2}
Below are some ways to achieve the task.
Method #1: Using Iteration
# Python code to count unique sublist within list # Input list initialization Input = [['Geek', 'for', 'geeks'], ['geeks', 'for'], ['for', 'Geeks', 'geek'], ['Geek', 'for', 'geeks']] # Output list initialization Output = {} # Using Iteration for lis in Input: Output.setdefault(tuple(lis), list()).append(1) for a, b in Output.items(): Output[a] = sum(b) # Printing output print(Output) |
chevron_right
filter_none
Output:
{(‘Geek’, ‘for’, ‘geeks’): 2, (‘geeks’, ‘for’): 1, (‘for’, ‘Geeks’, ‘geek’): 1}
Method #2: Using Counter
# Python code to find count of unique list in list of list # Importing counter from collection from collections import Counter # Input list initialization lst = [[1, 2, 3], [4, 5, 6], [3, 2, 1], [1, 2, 3]] # Using counter Output = Counter([tuple(i) for i in lst]) # Printing output print(Output) |
chevron_right
filter_none
Output:
Counter({(1, 2, 3): 2, (3, 2, 1): 1, (4, 5, 6): 1})
Method #3: Using Pandas
# Python code to count unique sublist within list # Importing from collections import Counter import pandas as pd # Input list initialization lst = [[1, 2, 3], [4, 5, 6], [3, 2, 1], [1, 2, 3]] # Getting count dict = Counter([tuple(i) for i in lst]) # Creating pandas dataframe Output = pd.DataFrame(data ={'list': list(dict.keys()), 'count': list(dict.values())}) # Printing output print(Output) |
chevron_right
filter_none
Output:
count list 0 1 (3, 2, 1) 1 1 (4, 5, 6) 2 2 (1, 2, 3)
Recommended Posts:
- Python | Count the sublists containing given element in a list
- Python | Print all sublists of a list
- Python | Remove repeated sublists from given list
- Python | Sort all sublists in given list of strings
- Python | Split a list into sublists of given lengths
- Python | Sort list of lists by the size of sublists
- Python | Split list of strings into sublists based on length
- Python | Get unique values from a list
- Python | Unique pairs in list
- Python | Assign ids to each unique value in a list
- Python | Get unique tuples from list
- Python | Assign value to unique number in list
- Python | Get Unique values from list of dictionary
- Python | Check if list contains all unique elements
- Python | Unique dictionary filter in list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



