Reputation: 241
I have just started to learn python and I wonder what is wrong with this for loop and/or if statement.
I am trying to loop through a list of words and if I find a word "right" I want to replace it with the word "left".
def left_join(phrases):
"""
Join strings and replace "right" to "left"
"""
mlist = list(phrases)
for word in mlist:
if word == "right":
word = "left"
output = ','.join(mlist)
return output
phrases = ("left", "right", "left", "stop")
left_join(phrases)
I am supposed to get this
"left,left,left,stop"
but I get
"left,right,left,stop"
So "right" is not replaced with "left". Why?
Upvotes: 0
Views: 76
Reputation: 2946
Try the following code:
def left_join(phrases):
"""
Join strings and replace "right" to "left"
"""
mlist = list(phrases)
for i in range(len(mlist)):
if mlist[i] == "right":
mlist[i] = "left"
output = ','.join(mlist)
return output
phrases = ("left", "right", "left", "stop")
output = left_join(phrases)
print(output)
Upvotes: 1
Reputation: 48406
Quoting the official documentation on for loop,
An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices.
So the mlist
does not change, only word
is changed here
Upvotes: 2