Thread shed: python

PLEASE HELP IM GOING CRAZY THINKING ABOUT THIS!!

in step 18 of this exercise. answer is:

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

in this exercise up to step number 18 there is only one big list with elements inside…
why do we have to put TWO layers of for loops?? isnt that only for when we have a list INside of another list? (2Lists)

why cant we do something like below??

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

LINK OF EXCERCISE BELOW:
https://www.codecademy.com/paths/computer-science/tracks/cspath-python-objects/modules/cspath-python-strings/projects/thread-shed

The split method will return a list. This what you are then iterating through in the inner loop.

3 Likes

thank you for your time but Why doesnt: for sale in thread_sold.split("&"): print a string around the split string?
instead of white&blue TO ‘white’, ‘blue’
doesnt .split(’&’) usually do ‘white&blue’ TO [‘white’, ‘blue’] ???

or am i missing something

I’m not quite sure what you mean. There’s no printing involved in split. 'white&blue'.split('&') would indeed return ['white', 'blue'].

Edit: I think the issue you’re trying to avoid is as follows-
lst = [‘blue’, ‘red’]
lst.append( ‘white&blue’.split(’&’))
print(lst)
Out: [‘blue’, ‘red’, [‘white’, ‘blue’]] # Note the new element in the list is itself a list.

If you want to avoid the second loop, which is perfectly reasonable, have a look at the extend method instead of append (which would append list itself rather than items in the list). I’m guessing extend has not been covered, at least not extensively, in previous lessons so the solution relies on two loops instead.

yes my issue was that i didnt know how ‘white&blue’.split(’&’) was returning ‘white’, ‘blue’ WITHOUT a string in the solution below:

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

but i kind of understand it more now. thank you