Python | Group list elements based on frequency
Given a list of elements, write a Python program to group list elements and their respective frequency within a tuple.
Examples:
Input : [1, 3, 4, 4, 1, 5, 3, 1]
Output : [(1, 3), (3, 2), (4, 2), (5, 1)]
Input : ['x', 'a', 'x', 'y', 'a', 'x']
Output : [('x', 3), ('a', 2), ('y', 1)]
Method #1 : List comprehension
We can use list comprehension to form tuples of each element and the count of its occurrence and store it in ‘res’, but that will contain the duplicate first element. Thus, to remove the duplicate first element, we use OrderedDict(res).items().
# Python3 program to Grouping list # elements based on frequency from collections import OrderedDict def group_list(lst): res = [(el, lst.count(el)) for el in lst] return list(OrderedDict(res).items()) # Driver code lst = [1, 3, 4, 4, 1, 5, 3, 1] print(group_list(lst)) |
[(1, 3), (3, 2), (4, 2), (5, 1)]
Method #2 : Using collections.Counter()
collections.Counter() provides two direct methods keys() and values() that provides the elements and its occurrences. At last, zip them together using Python zip() method.
# Python3 program to Grouping list # elements based on frequency from collections import Counter def group_list(lst): return list(zip(Counter(lst).keys(), Counter(lst).values())) # Driver code lst = [1, 3, 4, 4, 1, 5, 3, 1] print(group_list(lst)) |
[(1, 3), (3, 2), (4, 2), (5, 1)]
Recommended Posts:
- Python | Group tuple into list based on value
- Python | Add list elements with a multi-list based on index
- Python | Group elements on break positions in list
- Python | Group consecutive list elements with tolerance
- Python | Binary Group Tuple list elements
- Python | Group elements at same indices in a multi-list
- Python | List frequency of elements
- Python | Sort list elements by frequency
- Python | Find sum of frequency of given elements in the list
- Python | Filter list of strings based on the substring list
- Python | Filter a list based on the given list of strings
- Python | Group tuples in list with same first value
- Python | Group Anagrams from given list
- Python | Group strings at particular element in list
- Python | Group by matching second tuple value in list of tuples
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.



