I have a task to replace in each element of the list (with the help of the function replace() ) one substring for another. I do this by iterating through each item in the list and replacing the substring in it with forloop.

 array = ["one", "two", "three", "four", "five"] for a in array: a = a.replace("o", "zzzz") print(a) print(array) 

However, when displaying each element of the list in a loop and then outputting the entire list separately, I see that the list has not changed:

 zzzzne twzzzz three fzzzzur five ['one', 'two', 'three', 'four', 'five'] 

So why the list does not change?

    2 answers 2

    Just changing the lines is not enough. It is necessary to assign these modified lines to the elements of the list.

       array = ["one", "two", "three", "four", "five"] for i, a in enumerate(array): array[i] = a.replace("o", "zzzz") print(array[i]) zzzzne twzzzz three fzzzzur five print(array) ['zzzzne', 'twzzzz', 'three', 'fzzzzur', 'five'] 
      • I understand how to solve my problem with forloop. I am wondering for what reason the method I described above does not change the list. - BeerBaron
      • 2
        @BeerBaron because you did not change the list, you only changed the variable a , which is not associated with the list in any way - andreymal
      • @andreymal as I understand it, is the variable a a copy of the list item? - BeerBaron
      • @BeerBaron Any variable in python can be viewed as an object reference. The variable a initially refers to the same object that is stored in the list, but you didn’t change this object at all (and you can’t change the lines in python in principle, just create new ones), you only changed the link in the a variable that began to specify to another object (on a new line), and in the list both the old object was lying, and it continues to lie - andreymal
      • @andreymal understood, thanks - BeerBaron