Thread Shed Project

Step 18 Question: instruction: 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 .

when I added the following code, it worked but it created a sublist within a list. If I’m trying to do the next step to create a loop, I run into issues. I saw the solution but I’m trying to understand and find a simpler solution (if possible). Any suggestion?

thread_sold = [‘white’, ‘white&blue’, ‘white&blue’, ‘white’]

for color in thread_sold:
if “&” in color:

result = [‘white’, [‘white’, ‘blue’], [‘white’, ‘blue’], ‘white’]

The .split method always returns a list, even for an empty string. If you’re using append then consider what color.split(&) evaluates to (if unsure, print it). If you then replace that in your code you’d have some_list.append(?). Can you see why you’re getting sublists?

There are methods to deal with this sort of thing but perhaps you can work out a solution from the information you already know; that is, how to iterate through a list.

Thanks again for your feedback. So this is the solution, but I’m trying to understand at which point or iteration that the first ‘white’ gets added to the new_list?

thread_sold = [‘white’, ‘white&blue’, ‘white&blue’, ‘white’]
new_list =
for color in thread_sold:
\\for thread in color.split("&"):

new_list = [‘white’, ‘white’, ‘blue’, ‘white’, ‘blue’, ‘white’]

The best option is to get used to even some basic debugging by throwing in a print so you know what each identifier refers to at any one point. You can probably make a pretty good guess about it since the loops will be ordered so that the appends are also ordered.

Since there’s only one place where there is a an .append have a look there with print(thread) or even consider writing yourself a more useful message.

That kind of simple debugging is superb for things like loops, functions or almost anything where you’re not sure about the value. There’s no need to guess, you can test it and be sure. If you’re posting code to the forums have a look at: How do I format code in my posts?. It’ll explain how to avoid the format and indentation being removed by the forums which makes it much easier to read (especially for an indentation reliant language like Python).

1 Like