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

1 Answer

0 votes

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']


#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 Jun 12, 2020 in Python by Robindeniel
0 votes
asked Dec 16, 2021 in Hybrid Apps by sharadyadav1986
0 votes
asked Sep 22, 2021 in Python by sharadyadav1986