I need your help @List, Function

Hello Everyone,

I have some questions about the code of the three exercises below:


1, Use for, .split(), and if to create a Statement that will print out words that start with ‘s’:

st = ‘Print only the words that start with s in this sentence’

for word in st.split():
if word[0] == ‘s’: #<-- Here is what I don’t understand.
print(word)

And the output was correct:

start
s
sentence

Why it could work just simply by the code ‘ if word[0] == “s”:‘? I thought word[0] index the first item which is “Print” in st.split().


2, Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.

has_33([1, 3, 3]) → True
has_33([1, 3, 1, 3]) → False
has_33([3, 1, 3]) → False

def has_33(nums):
for i in range(0, len(nums)-1):

    if nums[i:i+2] == [3,3]:  # <--- Here is what I don't understand.
        return True  

return False

And the result was correct

I don’t understand why the part 'i+2 ’ in ‘if nums[i:i+2] == [3,3]’ , why not ‘i+1’ if another way to write this code is ‘if nums[i] == 3 and nums[i+1] == 3:’? Because what it wants id to return True if the array contains a 3 next to a 3 somewhere so why ‘i+2’??


3, PAPER DOLL: Given a string, return a string where for every character in the original there are three characters:
paper_doll(‘Hello’) --> ‘HHHeeellllllooo’
paper_doll(‘Mississippi’) --> ‘MMMiiissssssiiippppppiii’

def paper_doll(text):
result = ‘’ # <-- I’m not clear with this use ‘’
for char in text:
result += char * 3 # <-- I don’t understand here
return result

The result was correct:

‘HHHeeellllllooo’

‘MMMiiissssssiiippppppiii’

#But I don’t understand here:
for char in text:
result += char * 3

I thought ‘char * 3’ will get result like this “hellohellohello”…

Could somebody kindly explain all this to me? Thank you very much.

  1. if word[0] is targeting only the first character of that string, in case of “Print” it is just “P”.
    st.split() creates a list of strings, then for word in st.split() is looping over all strings and checking if the first character of each string is equal to “s”.

  2. Slicing with [a:b] means that it is going from a up to b, but it is excluding b. A bit weird but thats how it is, its the same in Javascript…

  3. This is a similar problem to your first question. This time it is not looping over strings, but characters in a string. for char in text loops over each character from a string, and then result += char * 3 adds each character 3 times in a row to the result string.

for ... in ... can loop over a sequence. A string or a list are both sequences, but the iterators are different, for a string it is characters, and for a list it is the elements of the list.

1 Like

Thank you so much. I enjoyed your explanation and I’m really more clear with the for…in… now.

1 Like