Categories

Dec 22, 2019 in Python

Q: How Do You Count The Occurrences Of Each Item Present In The List Without Explicitly Mentioning Them?

1 Answer

Dec 22, 2019

Unlike sets, lists can have items with the same values.

In Python, the list has a count() function which returns the occurrences of a particular item.

Count The Occurrences Of An Individual Item.

weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']

print(weekdays.count('mon'))

#output: 3

Count The Occurrences Of Each Item In The List.

We’ll use the list comprehension along with the count() method. It’ll print the frequency of each of the items.

weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon']

print([[x,weekdays.count(x)] for x in set(weekdays)])

#output: [['wed', 1], ['sun', 2], ['thu', 1], ['tue', 1], ['mon', 3], ['fri', 1]]

Click here to read more about Python
Click here to read more about Insurance

Related questions

Madanswer
Jun 12 in Python
Jun 12 in Python
May 17 in Python
...