0

I'm fairly new to Python, but have grasped most concepts fairly quickly.

I have written the following function to get the return figures of an array:

def getret(X):                                                                                                                          
    if X:                                                                       
        A = X                                                                   
        B = X                                                                   
        print(A)                                                                
        print(B)                                                                
        A.insert(0, 0)                                                          
        print(A)                                                                
        B.insert(len(X), 0)                                                     
        print(B)                                                                
        Z = []                                                                  
        for i in range(len(A)):                                                 
            Z.append(B[i]-A[i])                                                 
        print(Z)                                                                
        return Z                                                                
    return False   

The issue I am having is I want variables A and B to be treated completely independently, but it appears they are linked as they both refer to variable X.

When I feed this function the array [1,3,2,5,4] the results are output as follows:

[1,3,2,5,4]     # print A = X
[1,3,2,5,4]     # print B = X
[0,1,3,2,5,4]   # print A.insert(0, 0)
[0,1,3,2,5,4,0] # print B.insert(len(X), 0)
[0,0,0,0,0,0,0] # print list B - A

It appears When I amend A and B I actually change their reference X rather than the stored variable alone.

In JavaScript, I could easily sort this problem by setting A and B as local variables of X, but I have been unable to find such a succinct alternative in Python.

I am using PyCharm and Python 3.4.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
  • You should show what you mean about how you would do this in JS. AFAIK doing `var A = X; var B = X` would have exactly the same result as this Python code. – Daniel Roseman Sep 16 '15 at 09:59
  • You're right. I was able to do this in JavaScript, but it wasn't due to the use of the 'var'. Apologies. – alpacinohead Sep 16 '15 at 10:37

1 Answers1

4

no need to make a copy of X if you want an indepedent list:

A = X[:]

or even a deep copy if the elements in the list are more complex than numbers (that is not the case in your example):

from copy import deepcopy
A = deepcopy(X)

otherwise you just get a new reference to the same list.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111