LEARN PYTHON 3 - Thread Shed


I have a question related to the thread shed problem in Learn python 3.
Exercis here: https://www.codecademy.com/courses/learn-python-3/projects/thread-shed

I understand in the below example why we need a nested loop, since we have multiple of string in every array which then is a part of a bigger array:

daily_sales_replaced = daily_sales.replace(";,;", "+")
daily_transactions = daily_sales_replaced.split(",")

daily_transactions_split = []

for sale in daily_transactions:

transactions_clean = []
for sale in daily_transactions_split:
  transaction_clean = []
  for transaction in sale:
    transaction_clean.append(transaction.replace("\n", "").strip())

However, as you can se my code below, why do I need a nested loop to perfore the split of the colors?
The array constist of multiple string, but the string we which to split is already called with “sales” to my understand as it is one string and we want it to split to 2 or more depending on the number of “&”

customer = []
sales = []
thread_sold = []

for transaction in transactions_clean:

total_sales = 0

for sale in sales:
  total_sales += float(sale.strip("$"))

thread_sold_split = []

for sale in thread_sold:
  for color in sale.split("&"):

def color_count(color):
  count = thread_sold_split.count(color)
  return count

colors = ['red', 'yellow', 'green', 'white', 'black', ' blue', 'purple']

for color in colors:
  print("Thread shed sold {0} of {1} threads today".format(color_count(color), color))

Could someone be so kind to elaborate a bit on it for me to understand why this is the case?

Do you mean your last function?
It works. It’s just a different way to write the code to achieve the result.

No, the question is why I need a nested for-loop in the below code:

for sale in thread_sold:
  for color in sale.split("&"):

Because you’re looping though each sale and then each color in each sale and splitting the colors by the ampersand.

What happens when you remove the outer for loop?

It states that “.split()” can´t be run on lists which is correct of course.

But as far as i can understand, the string is for example “Red&yellow” i.e. we want to split that string and it should be one string, i.e. I don nut anderstand how we enter a string once we are already in it?

Thanks for the help Lisa!

The built in string method, .split() takes a string, splits it on the delimiter and returns a list of substrings.

Your inner for loop checks if it’s a single color or multiple color. If it’s a multiple color, ie:
'yellow&blue', 'yellow&blue&red' it splits that string into substrings, yellow, blue etc.

thread_sold_split = []

for sale in thread_sold:
  for color in sale.split('&'):


I don’t see where it says this in that project.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.