Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Dictionaries Word Count

Alperen Guman
Alperen Guman
6,552 Points

Element count in list without count() function weird behaviour

Code:

def word_count(x):
    word_count_dict = {}
    x = x.lower()
    string_to_words = x.split(' ')
    for words in string_to_words:
        n = 0
        while True:
            try:
                string_to_words.remove(words)
                n = n + 1
            except ValueError:
                break
        word_count_dict.update({words : n })
    print (word_count_dict)

word_count('some words more than others alperen guman')

Aim:

Getting a sentence string, making it lower case, splitting it into words and adding this to a list, then for every word running a loop to see how many times that word is in the original sentence and writing the resulting information to a dictionary.

Problem:

The code above should work, and it does work for the most part, but it skips over every other word. I can't figure out why. Help would be appreciated.

1 Answer

Alperen Guman
Alperen Guman
6,552 Points

Nevermind, found the solution. It was the fact that I was removing from the list I'm looping that was causing the problem. Here's a correct version of the code:

def word_count(x):
    word_count_dict = {}
    x = x.lower()
    string_to_words = x.split(' ')
    string_to_words_new = string_to_words[:]
    for words in string_to_words:
        n = 0
        while True:
            try:
                string_to_words_new.remove(words)
                n = n + 1
            except ValueError:
                break
        word_count_dict.update({words : n })
        string_to_words_new = string_to_words[:]

    print (word_count_dict)

word_count('some words more than others alperen guman')