Count in Python

In Python, counting occurrences of elements in a collection is a common task. This can be efficiently achieved using dictionaries, where keys represent the elements and values represent their counts. Below, we explore a function designed to count words in a list, demonstrating how to handle this task effectively.

The count_words Function

The count_words function is a utility that takes a list of words and returns a dictionary with each word as a key and its count as the value. This function is particularly useful for text analysis, where understanding the frequency of words is essential.

Basic Implementation

Here is a basic implementation of the count_words function:

def count_words(words):
    """takes list of cleaned words, returns count dictionary"""
    word_count = {}
    for word in words:
        count = word_count.setdefault(word, 0)
        word_count[word] += 1
    return word_count

Explanation

  • Initialization: The function initializes an empty dictionary word_count to store the word counts.
  • Iteration: It iterates over each word in the input list words.
  • Counting: For each word, it uses the setdefault method to initialize the word's count to 0 if it is not already in the dictionary. Then, it increments the count by 1.
  • Return: Finally, the function returns the word_count dictionary containing the frequency of each word.

Handling Non-Hashable Words

In some cases, the list of words might contain non-hashable elements, which would cause a TypeError when using them as dictionary keys. The following version of the count_words function includes error handling to skip such elements:

def count_words(words):
    """takes list of cleaned words, returns count dictionary"""
    word_count = {}
    for word in words:
        try:
            count = word_count.setdefault(word, 0)
        except TypeError:
            # if 'word' is not hashable, skip to next word.
            pass
        word_count[word] += 1
    return word_count

Explanation

  • Error Handling: The function wraps the setdefault method call in a try block. If a TypeError is raised (indicating a non-hashable word), the except block catches the error, and the function simply skips to the next word without incrementing the count.

This approach ensures that the function can handle a wider range of input data without failing due to unhashable elements.