0
   def f():
        list_0 = [1,2,3,4]
        p = [0,1,2,3,4,5,6,7,8]
        for i in list_0:
            x = p
            x[i] ="L"
            print(x)
            print(p)
    f()

Wanted the result to be: 0,"L",2,3,4,5,6,7,8 , 0,1,"L",3,4...... and so on , but got , 0,"L",2,3,4,5,6,7,8 , 0,"L","L",3,4,5,6,7,8.. so one, the "L" was getting saved . How do i change the code such that the variable p does not change and remains the same

  • `x = p` make x and p refer to the *same objects*. The *variable* isn't re-defined, you merely are mutating the same object, referenced by two different variables. – juanpa.arrivillaga Apr 28 '20 at 08:38
  • The problem simply happens because `x` gets assigned to the same `p`. So, when `x` changes, `p` gets changed as well. To fix that, you need to create a copy from `p` like so: `x = p.copy()` – Anwarvic Apr 28 '20 at 08:42
  • read the following: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Apr 28 '20 at 08:42

1 Answers1

0

Write your code in this way:-

def f():
    list_0 = [1,2,3,4]
    p = [0,1,2,3,4,5,6,7,8]
    for i in list_0:
        x = p.copy()
        x[i] ="L"
        print(x)
        print(p)
f()

Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17