0

So I'm doing an algorithm where you have to reverse each word in a string with Python. I've got a solution but why doesn't this piece of code change the list..

for i in l1:
   i = i[::-1]

Here l1 contains all string elements. Why does this not change l1 in any way?

  • Can you give an example of the input string and expected output string – Krishna Vaddepalli Sep 24 '20 at 03:44
  • 1
    You don't change the list anywhere in your code, nor do you mutate any of the element in the list. You instead create a *new string*, `i[::-1]` and then assign that to a variable, `i`. That doesn't affect either the string nor the list. – juanpa.arrivillaga Sep 24 '20 at 03:45
  • Hello, If you want reverse the list in that way you need a different list to store the result, but maybe you can do this in a better way, check this example: a = list(map(lambda x: x[::-1], a), first you need apply to the list a trasformation for each item, 'map' take each element and apply transformation method, lambda is a anonimous function that apply to each element for reverse the string, when used 'map' the result is a map's object then you need convert to list and replace the old list with the result of the map's object. – Jose Moreno Sep 24 '20 at 04:02

0 Answers0