-2

We have to take input of the length of the list from the User. Then count the frequency of each element in the list and print them using python.

I tried and here is the code :

l =  []
n = int(input("Enter the length of list : "))
for i in range(0,n):
    l.append(int(input("Enter an element : ")))
count = 0
for i in range(len(l)):
    for j in range(len(l)):
        if (l[i] == l[j]):  #Error
            count = count + 1
            l.pop(j)
    else:
        print("Count of ",l[i]," is ",count)
        count = 0
        l.pop(i)
else:
    print(l)

Getting error :

line 8, in if (l[i] == l[j]): IndexError: list index out of range

  • 2
    Why are you using `l.pop()`? – Guy Dec 11 '19 at 08:49
  • Using l.pop() so that it doesn't count the element which has already been counted for ex. if list is l =[1,2,1,4] then for l[0] count will be 2 but when it will go to l[2] then again it will show count 1. – Abhishek Tripathi Dec 11 '19 at 08:50
  • Does this answer your question? [How can I count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item) – mkrieger1 Dec 11 '19 at 08:57
  • Why are you using two nested loops? Imagine you would do this in real life: You have a bag with some fruit in it. Would you go through the whole bag twice (actually the code goes more than twice) to find out how many of each kind of fruit you have? – mkrieger1 Dec 11 '19 at 08:59

2 Answers2

0

l.pop is what causing the error, you are removing items from the list but still itreate to the original size. Use dict to count the frequencies

frequencies = {}
for item in l:
    if item in frequencies:
        frequencies[item] += 1
    else:
        frequencies[item] = 1

for key, value in frequencies.items():
    print(f'Count of {key} is {value}')

Or with get()

for item in l:
    frequencies[item] = frequencies.get(item, 0) + 1
Guy
  • 46,488
  • 10
  • 44
  • 88
-1

You can try this also (Python 3).

l =  []
n = int(input("Enter the length of list : "))
for i in range(0,n):
    l.append(int(input("Enter an element : ")))

s_list = set(l)
Count = []

print(l)
for ii in range(len(s_list)):
    Count.append(l.count(list(s_list)[ii]))

for ii in range(len(s_list)):
    print(list(s_list)[ii],": ", Count[ii])