Reputation: 342
I did the following:
mylist = ['pencil', 'dog', 'memo', 'Hello']
I want to flip each individual word like:
['licnep', 'god', 'omem', 'olleH']
I've tried the following:
for word in mylist:
word = word[::-1]
However, the above method doesn't work. Please explain.
Upvotes: 2
Views: 212
Reputation: 342
You should create a new list and append the flipped words in the new list.
Check the following code below:
mylist = ['pencil', 'dog', 'memo', 'Hello']
newlist = []
for word in mylist:
word = word[::-1]
newlist.append(word)
print(newlist)
Your code did not work because - For each iteration of the for loop, the variable word
is assigned with just a copy of the value of an item in mylist
, so changes made to word won't be reflected in mylist
. Here word
is just a local variable and it does not reference an item in mylist
.
Upvotes: 0
Reputation: 5570
You should use another list to save your changes because you should not modify the same list which you are looping over.
So you can fix your code like this:
mylist = ['pencil', 'dog', 'memo', 'Hello']
new_list = []
for word in mylist:
word = word[::-1]
new_list.append(word)
print(new_list)
Another way to reach the same goal is to use list comprehension.
Also in this case you are basically created a new list like this:
mylist = ['pencil', 'dog', 'memo', 'Hello']
newlist = [word[::-1] for word in mylist]
print(new_list)
Upvotes: 1
Reputation: 2334
The problem with your code
is that you are changing the word but not storing it in current list. You can use following script, if you want change in current list
mylist = ['pencil', 'dog', 'memo', 'Hello']
for word in range(len(mylist)):
mylist[word] = mylist[word][::-1]
print(mylist)
Output
['licnep', 'god', 'omem', 'olleH']
Upvotes: 1
Reputation: 1672
Actually, the above method is not making a change in the actual list. Try this:-
[word[::-1] for word in mylist]
Output:-
['licnep', 'god', 'omem', 'olleH']
Upvotes: 1