How to Count the Number of Categories in Python?

Estimated read time 1 min read

To count the number of categories in Python, you can use the built-in set() function to create a set of unique elements from a list. Here’s an example code snippet:

# Define a list of categories
categories = ["Sports", "Politics", "Entertainment", "Business", "Politics", "Technology", "Entertainment"]

# Use set() to get the unique categories
unique_categories = set(categories)

# Count the number of unique categories
num_categories = len(unique_categories)

# Print the result
print("There are", num_categories, "unique categories.")

In the above code snippet, we first define a list of categories that may contain duplicates. We then use the set() function to get the unique categories from the list, and store them in the unique_categories set.

Next, we use the len() function to count the number of elements in the unique_categories set, which gives us the number of unique categories. Finally, we print the result using the print() function.

Note that if your categories are stored in a data structure other than a list, you may need to convert them to a list before using the set() function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply