0 votes
in Python by
How Do You Count The Occurrences Of Each Item Present In The List Without Explicitly Mentioning Them?

1 Answer

0 votes
by

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
asked May 17, 2020 in Python by SakshiSharma
0 votes
asked May 17, 2020 in Python by sharadyadav1986
...