-1

The given problem - Given a string, return a string where for every character in the original there are three characters paper_doll('Hello') --> 'HHHeeellllllooo'

If I do this, I get the correct answer -

def paper_doll(text):
    s1 = list(text)
    for i in range(0,len(s1)):
        s1[i] = s1[i]*3
    s2 = "".join(s1)
    return s2

# Check
paper_doll('Hello')
'HHHeeellllllooo'

But this doesn't work -

def paper_doll(text):
    s1 = list(text)
    for i in s1:
        i= i*3
    s2 = "".join(s1)
    return s2

#Check
paper_doll('Hello')
'Hello'

Isn't i in the latter same as s1[i] in the former? What am I missing here?

  • 2
    You are not doing anything with `i` in the second example. Also, you do not access any character within `s1`. – Jan Apr 18 '20 at 19:43
  • Have you tried to debug/print your both trials? – Grajdeanu Alex Apr 18 '20 at 19:43
  • In the second loop, each time around, Python assigns each element of the list to the name “i”. But, “i” is just some temporary name for the element. It isn’t the element itself. –  Apr 18 '20 at 19:48
  • They are two very different things. The first loops over *the range object*, producing numbers that correspond to indices in your `list`. In the body, you then *mutate your list using these indices*, i.e. `s1[i] = s1[i]*3`. In the second loop, you *loop over the list itself*. You then assign to the local variable `i`, which also happens to be the variable target of the for-loop, `i= i*3`. This does *nothing to mutate the list*. If I did `x = s1[0]; x = 'foo'; print(s1)` then `s1` wouldn't be affected by the assignment to `x`. – juanpa.arrivillaga Apr 18 '20 at 19:48
  • Consider the first element of `s1`. The first loop does `s1[0] = s1[0]*3` which of course updates that element by multiplying it by 3 (which for strings just replicates the string 3 times). The second loop, however, does the equivalent of `i = s1[0]; i = i*3`, which assigns the value to `i`, updates `i` by multiplying it by 3, then discards the result, achieving nothing. – Tom Karzes Apr 18 '20 at 19:49
  • Thank you! I'm a novice programmer not yet clear with the basics. This did it. – Aditya Prakash Apr 18 '20 at 20:01

1 Answers1

1

You second version : i= i*3 just replaces the value assigned to the label(variable) i. i=H*3 which means HHH but does not replace the item inside the list as the first part of code does.

The context in first example is replacing the item inside the list.

andreis11
  • 1,133
  • 1
  • 6
  • 10