Problem: Given a list, find how many times a number is present in the list (i.e frequency) in Python.
Example:
1 2 3 4 5 6 7 8 9 | Example 1: Input - [13, 4, 4] Output - [(13, 1), (4, 2)] Example 2: Input - [6, 4, 5, 6, 1, 3, 7, 9, 5, 10, 6] Output - [(1, 1), (3, 1), (4, 1), (7, 1), (9, 1), (10, 1), (5, 2), (6, 3)] |
Recommended:
Python Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | def frequency_list(l): new = [] size = len(l) while size > 0: num = l[0] y=0 c=0 #conting frequency of each element while y < size and size >=1: if size ==1: y=0 if num == l[y]: index = l.index(num) l = l[:index] + l[index + 1 :] #removing the element which has already been counted c+=1 size-=1 else: y+=1 new.append((num,c)) #appending the (element, count) into list in the form of tupl return new |
Output
1 | print(frequency_list([6,4,5,6,1,3,7,9,5,10,6])) |
1 | [(1, 1), (3, 1), (4, 1), (7, 1), (9, 1), (10, 1), (5, 2), (6, 3)] |
1 | print(frequency_list([2,10,5,5])) |
1 | [(2, 1), (10, 1), (5, 2)] |
If you have any suggestion or doubts then comment below.