Thread Shed Excercise

Link to the exercise here: https://www.codecademy.com/courses/learn-python-3/projects/thread-shed

When using a nested loop, why does the following:

for thread in thread_sold:
for t in thread.split("&"):
print(t)

Print whole colours whereas:

for thread in thread_sold:
for t in thread:
print(t)

Just print out the individual letters of all the colours?

Of course I know the split function is splitting the colours at the “&” symbol but I’d have thought it would just still run through all the letters and split at the “&”.

I’m not entirely sure what you mean with the final line so apologies if this isn’t helpful. The split method always returns a list, even if it’s an empty one. Iterating though a list is farily straightfoward, it goes element by element. In one method you’re iterating through a list and in the other through a string.

Have a quick try for what happens when you iterate through a simple string-

for character in 'this string':
    print(character)

… comapred to what happens when you iterate through the output of split (even when no splits actually occur)-

for character in 'this string'.split('this substring'):
    # Using a weird substring which will cause no splits to show list behaviour.
    print(character)
2 Likes

Ahh I see thank you. So applying the method changes what you are iterating over? That was basically my question. So when we add “split” we’re saying iterate through the two strings created by the spit (or in this case the one string as there was nothing to split by)

That’s correct.

Remember the loop syntax for i in item implies item is iterable, but it helps to be clear about how you want it to iterate.

Some more examples

for i in 4:
   print(i)
>>> TypeError: 'int' object is not iterable

for i in str(4):
   print(i)
>>> 4

for i in range(4):
   print(i)
>>> 0
>>> 1
>>> 2
>>> 3

for i in reversed(range(0,4)):
	print(i)
>>> 3
>>> 2
>>> 1
>>> 0

for i in range(0, 4, 2):
	print(i)

>>> 0
>>> 2
2 Likes

Ahh makes sense thanks :slight_smile: