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().

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

[(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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

[(1, 3), (3, 2), (4, 2), (5, 1)]


My Personal Notes arrow_drop_up


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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.