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

0 votes
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]]

Related questions

0 votes
Jun 12, 2020 in Python
0 votes
0 votes
May 4 in JAVA
...