Thread Shed-Step 18: Why standard answer only append multiple color?

Hi everyone, need some help explaining why the standard answer in the walk-through video only appends elements in multiple color strings?

image

My code seems not to have a bug.

Could someone please give me a hand? I don’t understand how standard code achieve the task. Thanks.

The standard code (the code is the given video) does exactly the same thing as your code, it just assumes that there will always be a & in the given list. If you remove the if code and the else (just the else), then you will be left with:

for i in thread_hold:
  x = i.split('&')
  for u in x:
    #more code

You can condense the x = i.split('&') and for u in x lines to for u in i.split('&'). Then you’ll be left with:

for i in thread_hold:
  for u in i.split('&'):
    #more code

Which is just the same as the solution code-just with different variable names.
I hope this helps!

2 Likes

What confuses me is its assumption: there will always be a & in the given list. In that case, how does the standard code append the single color? I see that once you remove else, the rest is the same as the standard code. But what about the part after if before else?

If you check how the .spllit() method operates then it might clear up the confusion. See the docs- https://docs.python.org/3/library/stdtypes.html#str.split

For a quick example-

print('test'.split('&'))
Out: ['test']  # same string just in a list

If that’s still not clear play around with this e.g. 'test&test'.split('&') and get a for loop going through the results printing them out.

Thank you for your speedy response. Correct me if I’m wrong. So you are saying that sale.split(’&’) includes elements without ‘&’, which is single colors in this case? So for color in sales.split(’&’), actually those colors contain both single and multicolor?

Split will always return a list even if it’s just a list with an empty string as the sole element. If you wanted to know exactly what you’re getting from splitting on your colours/sales then try printing them out.

1 Like

Right. Now I totally understand. Thanks so much.

Feel I should add to this previous comment it is possible to return an empty list (and not just a list with a single empty string, ['']) from a string, [], if you were to use .split() on an empty string (or one with just whitespace) as per the docs- https://docs.python.org/3/library/stdtypes.html#str.split since that could wind up leading to a bug.

1 Like

Thanks for the clarification. I will avoid that when using .split().