Add the occurrence of each number as sublists in Python

PythonServer Side ProgrammingProgramming

We have a list whose elements are numeric. Many elements are present multiple times. We want to create sub list so the frequency of each element along with the elements itself.

With for and append

In this approach we will compare each element in the list with every other elements after it. If there is a match then count will be incremented and both the element and the count will be made into a subsist. List will be made which should contain subsists showing every element and its frequency.

Example

 Live Demo

def occurrences(list_in):
   for i in range(0, len(listA)):
      a = 0
      row = []
      if i not in listB:
         for j in range(0, len(listA)):
            # matching items from both positions
            if listA[i] == listA[j]:
               a = a + 1
            row.append(listA[i])
            row.append(a)
            listB.append(row)
      # Eliminate repetitive list items
      for j in listB:
         if j not in list_uniq:
            list_uniq.append(j)
      return list_uniq
# Caller code
listA = [13,65,78,13,12,13,65]
listB = []
list_uniq = []
print("Number of occurrences of each element in the list:\n")
print(occurrences(listA))

Output

Running the above code gives us the following result −

Number of occurrences of each element in the list:
[[13, 3], [65, 2], [78, 1], [12, 1]]

With Counter

We use counter method from the collections module. It will give the count of every element in the list. Then we declare a new empty list and add the key value pair for each item in form of element and its count into the new list.

Example

 Live Demo

from collections import Counter
def occurrences(list_in):
   c = Counter(listA)
   new_list = []
   for k, v in c.items():
      new_list.append([k, v])
   return new_list
listA = [13,65,78,13,12,13,65]
print("Number of occurrences of each element in the list:\n")
print(occurrences(listA))

Output

Running the above code gives us the following result −

Number of occurrences of each element in the list:
[[13, 3], [65, 2], [78, 1], [12, 1]]
raja
Published on 09-Jul-2020 12:41:07
Advertisements