Search code examples
pythonlistperformancedictionarynested-loops

Improved efficiency of a nested for loop counting into a dictionary - Python


I'm trying to filter out a list of stop words from a longer list of words, where the newly-filtered words and their counts become the key-values of a dictionary. The code I have will do this, but there are two issues:

  1. I thought I heard that nested for loops are frowned upon and to be avoided if possible
  2. The loop seems to take a while to finish (16.89223 seconds - on a 2019 MacBook Pro) . There are, however 3,476 key-value pairs as a result.

Am I over thinking this thing, or are there quicker ways to get the job done?

Here is the code:

words_cleaned = [...] # a long list of words from a Shakespeare play

stop_words = ["i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while", "of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now"]

go_word_counts = {}
go_words = []

for word in words_cleaned:
    if word not in stop_words:
        go_words.append(word)
    for word in go_words:
        if word not in go_word_counts:
            go_word_counts[word] = 1
        else:
            go_word_counts[word] += 1
       


    
go_word_counts

I appreciate your time, Nate


Solution

  • Consider using Counter

    from collections import Counter
    res = Counter([word for word in words_cleaned if word not in stop_words])