-2

For example, L = [1,2,2,3,4,9] Expected output: 1 occurred 1 times 2 occurred 2 times 3 occurred 1 times 4 occurred 1 times 9 occurred 1 times

Raza
  • 1
  • collections.Counter(l) – Buddy Bob May 27 '21 at 16:09
  • 2
    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) – jdabtieu May 27 '21 at 16:10
  • Welcome to stackoverflow, we expect you to do your research before posting a question. Searching [your question exactly](https://www.google.com/search?q=print+the+no+of+times+each+integer+in+a+list+occurred) will get you what you need. – Harshal Parekh May 27 '21 at 16:15

2 Answers2

2

Try this:

import collections

for k, freq in collections.Counter(L).items():
    print(f"{k} occurred {freq} times")
Shivam Roy
  • 1,961
  • 3
  • 10
  • 23
1

If you want to print these out as strings:

for i in set(L):
    print(f"{i} occurred {L.count(i)} times"

If you want to store these counts to use later in the code, use a dictionary: d = {i: L.count(i) for i in set(L)

not_speshal
  • 22,093
  • 2
  • 15
  • 30