Open In App

Python program to find number of likes and dislikes

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python provides various efficient ways to calculate the number of likes and dislikes from a list. count() method is the simplest and fastest way to count specific elements in a list.

Python
a = ["like", "dislike", "like", "like", "dislike"]

# Counting likes and dislikes
likes = a.count("like")
dislikes = a.count("dislike")

print("Likes:", likes)
print("Dislikes:", dislikes)

Output
Likes: 3
Dislikes: 2

Explanation:

  • count() counts the occurrences of a specific value in the list.
  • This method is efficient for small to medium-sized lists.

Let's explore some more methods to find the number of likes and dislikes in Python.

Using a Dictionary and Loop

A dictionary can be used to count likes and dislikes in a scalable way. This method is flexible and works well for larger lists or multiple reaction types.

Python
a = ["like", "dislike", "like", "like", "dislike"]

# Initialize dictionary
counts = {"like": 0, "dislike": 0}

# Count reactions
for reaction in a:
    if reaction in counts:
        counts[reaction] += 1

print("Likes:", counts["like"])
print("Dislikes:", counts["dislike"])

Output
Likes: 3
Dislikes: 2

Explanation:

  • Dictionary Initialization: the keys are "like" and "dislike" with initial values set to 0.
  • Loop iterates over the list and increments the count for each reaction.

Using collections.Counter

The Counter class from the collections module is a powerful tool for counting elements in a list. This method is highly efficient and concise for large datasets.

Python
from collections import Counter

# List of reactions
a = ["like", "dislike", "like", "like", "dislike"]

# Counting reactions
counts = Counter(a)
print("Likes:", counts["like"])
print("Dislikes:", counts["dislike"])

Output
Likes: 3
Dislikes: 2

Explanation:

  • Counter automatically counts the occurrences of each element in the list.
  • The resulting Counter object acts like a dictionary.

Using List Comprehension

List comprehension can also be used to filter and count specific reactions.

Python
# List of reactions
a = ["like", "dislike", "like", "like", "dislike"]

# Counting likes and dislikes
likes = len([reaction for reaction in a if reaction == "like"])
dislikes = len([reaction for reaction in a if reaction == "dislike"])

# Output
print("Likes:", likes)
print("Dislikes:", dislikes)

Output
Likes: 3
Dislikes: 2

Explanation:

  • Filtering Filters the list for "like" and "dislike" using a conditional.
  • The len() function calculates the count of the filtered list.
  • This method is less efficient but demonstrates the use of list comprehensions.

Similar Reads