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
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
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]
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()]