Thread Shed Project Step 18: Official Solution does not do what is asked. My code failed and I would like to know why

So, step 18 of the Thread Shed exercise - Strings Chapter asks for:

Next, iterate through thread_sold. For each item, check if it is a single color or multiple colors. If it is a single color, append that color to thread_sold_split. If it is multiple colors, first split the string around the & character and then add each color individually to thread_sold_split .

However, the video walkthrough solution does not solve it that way. The dev says it is not necessary to check, since .split("&") will only act on the items that have the β€œ&” anyway. So he solved it like this:

thread_sold_split = []
for sale in thread_sold:
  for color in sale.split("&"):
    thread_sold_split.append(color)

I did try to check using the code below, though, but it did not work. I expected to append the collors individually but it keeps appending the lists of colors that were generated on the split.

thread_sold_split = []
for item in thread_sold:
  if "&" in item:
    splitted_item = []
    splitted_item.append(item.split("&"))
    for singlecolor in splitted_item:
      thread_sold_split.append(singlecolor)
  else:
    thread_sold_split.append(item)

I would like to know why this code is not working, since I can’t check the solution to find out because the solution went through a different path.

Thanks,

Felipe

Hello, @dev1260752192, and welcome to the forums.

The best way to find out what is happening with a block of code is to observe what exactly it is doing. We can do that with print() statements. Try the following, and see if the output is what you expect.

thread_sold_split = []
for item in thread_sold:
  print(item) #debug print
  if "&" in item:
    splitted_item = []
    splitted_item.append(item.split("&"))
    print(splitted_item) #debug print
    for singlecolor in splitted_item:
      print(singlecolor) #debug print
      thread_sold_split.append(singlecolor)
  else:
    thread_sold_split.append(item)
1 Like