-2

I'd like to know why the variables were not reassigned when I used the for loop.

def master_yoda(text):
    wordlist = text.split()
    for word in wordlist:
        word = word[::-1]
    return wordlist
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

2 Answers2

0

The variable word was reassigned, but if you want to change wordlist you need to do something like this:

def master_yoda(text):
    wordlist = text.split()
    for idx, word in enumerate(wordlist):
        wordlist[idx] = word[::-1]
    return wordlist

EDIT -> You could also do this:

def master_yoda(text):
    return text[::-1].split()[::-1]
David Camp
  • 322
  • 2
  • 9
  • Thanks David. This works well. what happens in the earlier code though? when word is reassigned, what happens to it? – Prince Lloyd May 24 '22 at 11:04
  • @PrinceLloyd The variable `word` doesn't represent the actual value inside `wordlist`, just a copy of it, so the changes you make to `word` won't actually change `wordlist`. What happens in your code is that at the start of the `for` loop `word` is assigned to a copy of `wordlist[0]` then it is reassigned to `word[::-1]`, then, when the loop continues, it is reassigned to a copy of `wordlist[1]` and so on... All that without changing `wordlist`. Hope that explained a bit better – David Camp May 24 '22 at 13:40
  • @PrinceLloyd I added to my answer a simpler way to achieve the same result – David Camp May 24 '22 at 13:54
-1

First of all when you do a slice in Python, ex:

// strings are basically arrays of characters
array = [1,2,3,4]
_slice = array[start:end:step]

It makes a COPY of the array. Second, you are not actually referencing text, you are referencing the copy generated by text.split(). Do something like

def master_yoda(text):
  words = []
  for word in text.split():
    words.append(word[::-1])
  return words

Or with list comprehension:

def master_yoda(text):
  return [word[::-1] for word in text.split()]
ben10mexican
  • 51
  • 1
  • 5