Thread Shed Project

Hello, I am working on the Thread Shed project for the python course. https://www.codecademy.com/courses/learn-python-3/projects/thread-shed

I have a question regarding steps 19 and 20.

I watched the walkthrough video on this project. I followed what the instructor did in the video for the color_count function:

def color_count(color): color_total = 0 for thread_color in thread_sold_split: if color == thread_color: color_total += 1 return color_total

However, that returns 0 rather than 28 as it does in the video.

I did find another way to get it to return the correct amount by switching the == to in

def color_count(color): color_total = 0 for thread_color in thread_sold_split: if color in thread_color: color_total += 1 return color_total

I’m a little confused why the == worked in the video walkthrough but not when I applied it in my own code. It makes sense to me that == would work so I’m having a little bit of trouble understanding why it won’t.

Any help would be great. Thanks!

I don’t know if the walkthrough video is available for public viewing, so I can’t see what is being done in the video.

But, by the time you reach Step 19, thread_sold_split will be a list of lists i.e. having a structure of

[['white'], ['white', 'blue'] ... ]

You can view how the data is structured by using a print statement such as print(thread_sold_split).

With the above in mind, look at your first code snippet. color is supposed to be a string. The loop will traverse the thread_sold_split list by assigning each sublist to the loop variable thread_color. Even though the loop variable is named thread_color in the snippet, it is a misleading name. In the first snippet, thread_color doesn’t hold a string value. Rather a list of string (or strings) is assigned to thread_color. The if condition

if color == thread_color:

ends up comparing a string to a list (of string(s)) which will always be false. Hence, color_total is never incremented and remains 0.
You want to nest another loop to iterate over the colors in the sublists,

for thread_color_list in thread_sold_split:
    for thread_color in thread_color_list:
        if color == thread_color:
            color_total += 1

Now, it should work.

The second snippet works without the need of a nested loop. In the first snippet, comparing a string to a list doesn’t work. In the second snippet, you are using in to check whether a string is present in a list of string(s). That is valid as the in keyword delegates the task of traversing the sublist to Python, rather than you having to write a nested loop to iterate over the strings in the sublists.