Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a list of list by value and not reference [duplicate]

To understand why I was getting an error in a program , in which I tried to find the "minor" of a determinant, I wrote a simpler program because my variables were messed up. This function below takes in a 2 * 2 matrix as an input, and returns a list containing its rows (pointless and inefficient, I know, but I'm trying to understand the theory behind this).

def alpha(A):   #where A will be a 2 * 2 matrix
    B = A       #the only purpose of B is to store the initial value of A, to retrieve it later
    mylist = []
    for i in range(2):
        for j in range(2):
            del A[i][j]
        array.append(A)
        A = B
    return mylist

However, here it seems that B is assigned the value of A dynamically, in the sense that I'm not able to store the initial value of A in B to use it later. Why is that?

like image 620
Sphener Avatar asked Nov 02 '16 14:11

Sphener


3 Answers

Because python passes lists by reference

This means that when you write "b=a" you're saying that a and b are the same object, and that when you change b you change also a, and viceversa

A way to copy a list by value:

new_list = old_list[:]

If the list contains objects and you want to copy them as well, use generic copy.deepcopy():

import copy
new_list = copy.deepcopy(old_list)
like image 134
Nikaido Avatar answered Oct 22 '22 00:10

Nikaido


Since Python passes list by reference, A and B are the same objects. When you modify B you are also modifying A. This behavior can be demonstrated in a simple example:

>>> A = [1, 2, 3]
>>> def change(l):
...     b = l
...     b.append(4)
... 
>>> A
[1, 2, 3]
>>> change(A)
>>> A
[1, 2, 3, 4]
>>> 

If you need a copy of A use slice notation:

B = A[:]

like image 28
Christian Dean Avatar answered Oct 22 '22 00:10

Christian Dean


A looks like a reference type, not a value type. Reference types are not copied on assignment (unlike e.g. R). You can use copy.copy to make a deep copy of an element

like image 1
Christian Sauer Avatar answered Oct 21 '22 23:10

Christian Sauer