List values are changing after passed into function

2710 views python
4

The idea was to have static values for the list 'a', but its contents seems to be changing once this list pass through the operation of a function.

a = [1, 3, 5]
u = []

def f(a1, num):
    x = []
    n = len(a1)
    for i in range(n):
        a1[i] = a1[i] + num
        x.append(0)
    for i in range(n):
        x[i] = x[i] + a1[i]
    #a1 = a2
    return x

u = f(a, 10)
print "u = ", u 
print "a = " ,a 

u = f(a, 100)
print "u = ", u 
print "a = " ,a 

The output is:

u =  [11, 13, 15] 
a =  [11, 13, 15]  
u =  [111, 113, 115]  
a =  [111, 113, 115]  

I've been trying to create a copy of the list and hope to mantain the original values, but still nothing.

Any ideas are really appreciated :)

answered question

u = f(a.copy(), 10)

2 Answers

8

Have you tried copying the list like this?

u = f(a[:], 10)

posted this
9

I would make a copy of the list, and no, not copy = a but instead,

copy = []
for value in a :
    copy.append(value)

posted this

Have an answer?

JD

Please login first before posting an answer.