1

I can't understand why this simple code produces the results it does, I have tried to search for another similar question but I've not been sure on the correct vocabulary to use. Here is the code in question.

def test(f):
    f.append(0)
    f.append(0)
    return f

i = [0] * 6
f = i

print(i)
f = test(f)
print(i)

The result it produces in python 3.7

[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0]

I'm no expert in python but I really don't understand how the value of i is dependant on the value of f. The value of f is dependant at the start on the i but that way only. I would have expected to see both the lists to be identical when printed. The function doesn't recognise the i list and yet changes it either side of the function.

Obviously when the f list is printed the results are expected but I was hoping to explain what was happening here with i.

Oculo
  • 11
  • 1
  • `f` in `test` is just a reference (as is `f = i`), not a copy. So in the end, you're changing the list `i` within `test()`. `f` and `i` refer to the same object, a list in your case. – Jan May 02 '20 at 11:31
  • You probably want to copy the list, e.g. `f = i[:]` - in this case a separate object is created. – MrBean Bremen May 02 '20 at 11:55

4 Answers4

0

f and i are the same object.

So:

f=i
f.append(0)
f.append(0)

Modifies f as well as i.

To have them completely unrelated and to only make a copy:

f = i.copy()

Here appending something to f will only modify f as it is a copy and not the same object.

0

When your making a list in python it creates a object. This object is referenced by i to start with. When you use f = i, then they both have a link to the same object. this object link is sent into the function and is changed.

To avoid this issue you need to create a copy of it. This can be done through the copy module.

0

f in test() is just a reference (as is f = i), not a copy. So in the end, you're changing the list i within test(). f and i refer to the same object, a list in your case.
If you do not want this behaviour, you'll need

f = i.copy()
Jan
  • 42,290
  • 8
  • 54
  • 79
0

There is no concept of a dependent and an independent variable in python. List f is a reference of list i, so any change in f would reflect in i and vice versa.

agastya
  • 366
  • 1
  • 6